在多个线程中使用线程安全单例的示例

时间:2021-08-22 20:55:39

There is thread safe singleton, but when we use singleton in multiple threads? When it may be helpful?

有线程安全的单例,但是当我们在多个线程中使用单例时?什么时候有帮助?

1 个解决方案

#1


1  

I use stateless singletons as implementations of a strategy. Being stateless, they are also thread safe and there is no problem testing them.

我使用无状态单例作为策略的实现。作为无状态,它们也是线程安全的,测试它们没有问题。

Where you get into problems is with stateful singletons. This leads to more interactions, especially in a multi-thread context, but just unit testing a stateful singleton in one thread is a pain (i.e. you have to reset the state between tests). For this reason, many see singletons as an anti-pattern to be avoided.

你遇到问题的地方是有状态的单身人士。这会导致更多的交互,特别是在多线程上下文中,但只是在一个线程中单元测试有状态单例是一种痛苦(即你必须在测试之间重置状态)。出于这个原因,许多人认为单身人士是一种可以避免的反模式。

A better approach to stateful singletons is to use dependency injection. This way the code building the components only create one object, and that is passed to all the components which need it.

有状态单例的更好方法是使用依赖注入。这样构建组件的代码只创建一个对象,并将其传递给需要它的所有组件。

#1


1  

I use stateless singletons as implementations of a strategy. Being stateless, they are also thread safe and there is no problem testing them.

我使用无状态单例作为策略的实现。作为无状态,它们也是线程安全的,测试它们没有问题。

Where you get into problems is with stateful singletons. This leads to more interactions, especially in a multi-thread context, but just unit testing a stateful singleton in one thread is a pain (i.e. you have to reset the state between tests). For this reason, many see singletons as an anti-pattern to be avoided.

你遇到问题的地方是有状态的单身人士。这会导致更多的交互,特别是在多线程上下文中,但只是在一个线程中单元测试有状态单例是一种痛苦(即你必须在测试之间重置状态)。出于这个原因,许多人认为单身人士是一种可以避免的反模式。

A better approach to stateful singletons is to use dependency injection. This way the code building the components only create one object, and that is passed to all the components which need it.

有状态单例的更好方法是使用依赖注入。这样构建组件的代码只创建一个对象,并将其传递给需要它的所有组件。