java - OSGI DS @Reference 中的原子引用

标签 java osgi apache-karaf declarative-services

我正在编写一个 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/

相关文章:

java - Apache Karaf Bundle 上下文监听器

java - 在 Java 文件中创建时,表列分布不均匀

java - 如何使用 Android 获得最准确的时间?

java - 在 OSGi 环境中开始使用捆绑 DI

struts2 - 非 osgi 与 osgi 包交互

apache-karaf - Apache Karaf 中的功能、捆绑、依赖、先决条件和要求之间有什么区别?

osgi - Apache Karaf 如何对要安装和启动的包进行排序?

java - 使用 spring 中的 Rest 模板通过 post 调用发送 json 数据

java - 如何将天数添加到字符串数据类型的 jtextfield 中给定的日期

java - 下载 Java EE API JAR 作为 OSGI 包