简体   繁体   English

单例/静态会影响多线程Java应用程序的性能吗?

[英]Singleton / Static Affects performance of Multi-Threaded Java Application?

Does use of Singleton / Static slows down Multi-Threaded Application (running on multi-core system)? 使用Singleton / Static是否会减慢多线程应用程序(在多核系统上运行)? I was running an application creating 6 threads on 8 core machine. 我正在运行一个在8核计算机上创建6个线程的应用程序。 Initially a few singleton objects shared among all the thread. 最初,所有线程之间共享一些单例对象。 And I was not getting the the expected performance boost for going from single-threaded to multi-threaded model. 从单线程模型到多线程模型,我并没有获得预期的性能提升。 After this I change my code so that there is no singleton or static (ie tried not to share anything among the threads) and I got a performance boost of approx 6 times. 在此之后,我更改了代码,以使没有单例或静态(即,尝试在线程之间不共享任何内容),并且性能提高了大约6倍。 Can somebody please explain the behavior? 有人可以解释一下这种行为吗?

  1. static has definitely nothing to do with slowdowns. static绝对与减速无关。 In fact, static fields are the fastest of all to access. 实际上,静态字段是访问速度最快的字段。

  2. Singletons by themselves are not an issue either. 单身人士本身也不是问题。 You may have lazily initialized singletons, whose accessor methods are synchronized . 您可能有延迟初始化的单例,其访问器方法是synced In this case your code ss just using the wrong idiom. 在这种情况下,您的代码仅使用了错误的惯用法。 The idiom of choice for static singletons is the lazy initialization holder class , which incurs zero penalty and is completely thread-safe. static单例的选择习惯用法是惰性初始化持有者类该类产生零惩罚并且是完全线程安全的。

  3. It may also be the case that the methods you call on singletons need synchronization. 在单例上调用的方法也可能需要同步。 Usually, if we are using mutable singletons at all, it is because we have no choice but to use them. 通常,如果我们完全使用可变单例,那是因为我们别无选择,只能使用它们。 If you do have such choice, then by all means avoid singletons. 如果您确实有这样的选择,那么一定要避免单例。

For optimum performance, uphold these simple rules: 为了获得最佳性能,请遵循以下简单规则:

  1. share as little mutable state as possible. 共享尽可能少的可变状态。 Mutation needs mutual exclusion and hurts performance; 变异需要相互排斥,并损害绩效;

  2. share as much immutable state as possible. 共享尽可能不变的状态。 This will reduce CPU cache misses and improve performance. 这将减少CPU缓存丢失并提高性能。

There are many issues with stateful singletons, but what you are describing sounds more like contention for the singleton object. 有状态单例有很多问题 ,但是您所描述的听起来更像是对单例对象的争用 That is, you had a slowdown because your singleton(s) were synchronizing on something. 也就是说,您的速度变慢了,因为您的单身人士正在同步某些事物。 In that case, the multi-threaded version may not be doing the same thing; 在这种情况下,多线程版本可能做的不一样。 that is, you may have traded a performance problem for a race condition . 也就是说,您可能已经将性能问题换成了竞争条件 You need to show us more detail of your code for a more specific answer. 您需要向我们显示代码的更多详细信息,以获得更具体的答案。 As is, pretty much just guessing. 照原样,几乎只是猜测。

BTW, IMHO state less singletons are best handled as enum . 顺便说一句,恕我直言,状态少的单例最好作为enum来处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM