开发者

singleton and performance

Hi: I have a multi thread Java program. There are many singletons. I am wondering whether singleton would decrease the performance of a multi thread program, especially throughput. Some Singleton is simply a single object, some singleton are concurrentHashmap an开发者_如何转开发d/or atomicinteger.


If your singletons are immutable then they won't cause a decrease in performance.

However as you said, if there are concurrent (synchronized) data structure singletons in your code then your performance will be decreased when compared to non-concurrent data structures.

Basically, think objects as data holders with some methods on them and now think that you have a linked list in your code and many threads are running concurrently and modifying that linked list. Analogous to this example, your singleton data structure is data holder and many threads are trying to update it and the system is staying consistent with locks.

Long story short, I don't think that having singletons in concurrent systems will make a significant difference in performance unless they hold a data structure updated by multiple threads.


If you synchronize on any object, all threads will have to wait to obtain a lock on that object, before execution of the synchronized block of code. Other threads will queue up, waiting for the lock to be released. By inference, synchronizing on singleton instances or the singleton class will result in a decrease in performance. In simpler words, the performance decrease is a factor of how granular the lock is; if you synchronize on a singleton having n methods, all threads will have to wait on only one lock, even if they attempted to execute the n different methods.

If you can, redesign your application, to not synchronize on singletons in performance hot spots. Given, that you are using classes that were designed for concurrent access, this might not be a problem. This better than attempting to reduce lock contention on the singleton.

On the other hand, if you are not synchronizing on the singleton at all (intentionally, because there is no shared data), then using singletons would not result in a performance decrease.


The only overhead by having singletons is synchronization overhead , because the singleton objects usually have state. If they do not have state, it is like any other java method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜