我正在编写一个 OSGI 应用程序,其中包括动态和静态引用。每个服务都放置在不同的 bundle 中。
@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);
}
没有原子引用
@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;
}
建议使用哪一种?每种对性能的影响是什么?
最佳答案
事实上,您将 @Reference 放在字段上意味着您正在使用 DS 1.3 及其新的字段注入(inject)支持。
在这种情况下,您不需要绑定(bind)/取消绑定(bind)方法,也不需要 AtomicReference。只是:
@Reference
私有(private) volatile TestService testService;
volatile 意味着它是动态引用,并且还提供适当的并发访问。
关于java - OSGI DS @Reference 中的原子引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35224151/