java - 单例对多线程的性能影响有多大?
巴扎黑
巴扎黑 2017-04-17 17:09:01
0
3
801

我抽象了一个连接管理类, ConnectionManager, 主题类TopicManager,可能还有更多.

  1. 就拿这个TopicManager来说, 我的程序主要就是用发布订阅的模式实现通讯, 也就是TopicManager的访问读取会非常频繁. 因为是单例的, 我肯定要做线程同步处理, 这样在多线程下对性能的影响有多大了?

  2. 相比之下, 我如果取消TopicManager这个类, 直接对数据库操作, 通过c3p0连接池, 以上两种方法相比, 哪种开销更大.

多谢各位.

巴扎黑
巴扎黑

reply all(3)
迷茫

Singleton and multi-threading are two completely unrelated fields. Singleton solves the problem of controlling objects, while multi-threading solves the problem of making full use of the capabilities of multi-core processors.
It does not mean that singletons must be synchronized. Synchronization is only required when data sharing occurs. So even if you do not use singletons, but multiple objects share a resource, they still need to be synchronized; the same Reasonable, even if you use a singleton, if you don't share resources, you still don't need synchronization.

A practical example:
Now there is a singleton, but the singleton method does not use any static objects, that is, there is no resource sharing, so synchronization is not required.

伊谢尔伦

Personal understanding: If a singleton considers multi-threading, it must be locked, and the performance will definitely be affected. Depending on the business situation, consider using threadLocal

Ty80

Single cases are read-only. . There is no impact. .

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template