我正在编写一个OSGI应用程序,其中包括动态&静态引用。每项服务都放在不同的包中。
@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;
}
推荐哪一个以及每个产品对性能的影响是什么?
答案 0 :(得分:3)
您将@Reference放在字段上意味着您正在使用DS 1.3及其新的字段注入支持。
在这种情况下,您不需要bind / unbind方法也不需要AtomicReference。只是:
@Reference
private volatile TestService testService;
volatile意味着它是一个动态引用,并提供适当的并发访问。