线程安全的对象 - 静态或不是?线程、静态、对象、不是

由网友(触不可及,而又念念不忘)分享简介:我最近在接受采访时和科技人问我如何让应用程序线程安全的。好了,解释了锁后()正确的,他说这是不是有对象为静态是个好主意。私有静态只读对象_syncLock =新的对象();他宣称的原因是静态的品牌是反对较慢线程锁定比,如果它是非静态的。这是真的吗?编辑:不过我现在还不能确定。这三种方法之间的区别是什么?私有静态只读对...

我最近在接受采访时和科技人问我如何让应用程序线程安全的。

好了,解释了锁后()正确的,他说这是不是有对象为静态是个好主意。

 私有静态只读对象_syncLock =新的对象();
 

他宣称的原因是静态的品牌是反对较慢线程锁定比,如果它是非静态的。这是真的吗?

编辑: 不过我现在还不能确定。这三种方法之间的区别是什么?

 私有静态只读对象_syncLock =新的对象();
公共静态只读对象_syncLock =新的对象();
私人只读对象_syncLock =新的对象();
 

解决方案 技术分享 JAVA线程安全之内存模型

如果一个锁定对象应该是静态的,取决于你想要锁定的对象。如果你想锁定一个类的实例,你不能用一个静态的锁定对象。如果你想锁定的静态数据不能用一个实例锁定对象。所以似乎没有任何的选择。

您可以考虑使用静态或实例锁定对象锁定访问实例数据,但这会导致不同的行为。通过一个实例锁定对象,你只能锁定一个实例,而一个静态锁对象将锁定所有实例。因此,这里的性能调优别无选择了。

I was recently in an interview and the tech guy asked me about how to make an application thread-safe.

Well, after explaining the lock() correctly, he said it is not a good idea to have the object as static.

private static readonly object _syncLock = new object();

He claimed the reason is that static makes that object slower for threads to lock than if it was non static. Is this true?

EDIT: Nonetheless I am still not sure. What is the difference between these three approaches?

private static readonly object _syncLock = new object();
public static readonly object _syncLock = new object();
private readonly object _syncLock = new object();

解决方案

If a lock object should be static or not depends on the object you want to lock. If you want to lock an instance of a class you cannot use a static lock object. If you want to lock static data you cannot use an instance lock object. So there seems not to be any choice.

You could think about using a static or an instance lock object to lock the access to instance data, but this results in different behaviors. With an instance lock object you lock only an instance while an static lock object will lock all instances. So no choice for performance tuning here, too.

阅读全文

相关推荐

最新文章