2016-02-05 102 views
0

我正在寫一個OSGI應用程序,其中包含動態&靜態引用。每個服務都放在不同的包中。OSGI中的原子參考DS參考

@Reference (bind = "bindMethod", unbind = "unbindMethod", cardinality = ReferenceCardinality.MANDATORY_UNARY, policy = ReferencePolicy.DYNAMIC) 
    private final AtomicReference<TestService> testService = new AtomicReference<TestService>(); 

@Reference (bind = "bindMethod", unbind = "unbindMethod", cardinality = ReferenceCardinality.MANDATORY_UNARY, policy = ReferencePolicy.DYNAMIC) 
    private AtomicReference<TestService> testService = new AtomicReference<TestService>(); //final is ommitted 

protected void bindMethod(TestService atestService) 
    { 
     if (TestService.get() == null) 
     { 
      testService.set(atestService); 
     } 
    } 

    protected void unbindMethod(TestService atestService) 
    { 
     myServices.compareAndSet(testService, null); 
    } 

沒有的AtomicReference

@Reference (bind = "bindMethod", unbind = "unbindMethod", cardinality = ReferenceCardinality.MANDATORY_UNARY, policy = ReferencePolicy.DYNAMIC) 
    private TestService testService; 

protected void bindMethod(TestService atestService) 
    { 
     testService = atestService; 
    } 

    protected void unbindMethod(TestService atestService) 
    { 
     testService = null; 
    } 

哪一個建議,什麼是每一個對性能的影響?

回答

3

事實上,您將@Reference放在字段上意味着您正在使用DS 1.3及其新的字段注入支持。

在這種情況下,您不需要bind/unbind方法和AtomicReference。剛:

@Reference private volatile TestService testService;

揮發性意味着它是一個動態的參考,還提供了適當的併發訪問。

+0

感謝哈格雷夫。我將用於剛開始/停止某些服務的服務。由於有一個Atomic Reference,它在內部使用某種併發邏輯。在這個普通的動態服務中對併發/同步化有什麼需求?當我使用AtomicReference時性能影響是什麼,我不是? – Shriram

+0

您的評論與BJ已經回答的主要問題似乎沒有什麼不同。 –

+0

你不需要使用AtomicReference。 DS會處理管理該字段的值,並且由於它是不穩定的,您將擁有適當的併發行爲。 –