本文介绍了如何在Java Singleton中维护可变状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用Java开发的Singelton(在OSGi服务中),并且想要在其中维护某些状态(一个计数器).

I have a Singelton in Java (in an OSGi Service) and want to maintain some state in it (a counter).

此变量应该是静态的吗?或同步?还是两者都有?

Should this variable be static? or synchronized? or both?

还是应该将这些动作包装在一个同步方法中? (这与使var同步化会有什么不同吗?)

Or should i wrap the actions in a syncronized method? (would this be any different than just making the var syncronized?)

我希望服务操作的使用者增加此计数器.

I want consumers of the service actions to increment this counter.

public MyServiceImpl implements MyService {
    private int count = 0; // static? syncronized?

    public String helloWorld() { count++; return "Hello World"; }
    public int getHelloCount() { return count; }
}

更新:我怎么会喜欢地图或列表?是否也首选使用这些版本的Atomic版本?还是同步更好呢?

Update: How would I so something like a Map or a List? Is it preferred to use Atomic versions of these too? Or is Synchronized better for this?

推荐答案

单例的问题在于它们需要作用域.如果您在OSGi中注册服务,则这是框架中的单例.但是,由于OSGi避免了类似鼠疫的静息,因此人们可以在同一VM中启动多个框架(嵌套或兄弟姐妹),这可能意味着您的服务已在不同框架中多次注册.通常,这正是您想要的.如果单身还不够,那么范围应该是什么? VM,进程,机器,网络,世界?人们为您提供的用于创建单例的所有技巧都忘记了告诉您它们仅适用于您碰巧所在的类加载器.

The problem with singletons is that they require a scope. If you register a service in OSGi then this is a singleton in the framework. However, since OSGi avoids statics like the plague people could start multiple frameworks (nested or as siblings) in the same VM and that could mean your service gets registered multiple times in different frameworks. In general, this is exactly what you want. If this not sufficiently singleton, then what should be the scope? The VM, the process, the machine, the network, the world? All the tricks people provide you for creating singletons forget to tell you that they scope only for the class loader you happen to be in.

在OSGi中,假设您的范围是框架.因此,只需注册一个服务并使用实例变量.由于OSGi在并发环境中运行,因此,正如所有其他文章所指出的那样,您必须使用同步方法或更好的AtomicLong/AtomicInteger.

In OSGi, assume your scope is the framework. So just register a single service and use instance variables. Since OSGi runs in a concurrent environment, you must, as all the other posts indicate, use synchronized methods or better AtomicLong/AtomicInteger.

如果您有多个服务需要共享一个单身人士,只需创建一个额外的服务来代表该单身人士.

If you have multiple services that need to share a singleton, just create an extra service to represent the singleton.

永远不要使用静态变量,因为它们会大大降低代码的可重用性,它们具有全局变量的所有弊端.纯OSGi的优点之一是,它允许您几乎完全使用实例进行编程,而不必使用静态变量和类名(它们具有相同的全局变量问题).

Never use statics since they can reduce the reusability of your code significantly, they have all the evils of global variables. One of the beauties of pure OSGi is that it allows you program almost completely with instances and never have to work with statics and class names (which suffer from the same global variable problem).

这篇关于如何在Java Singleton中维护可变状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 06:18