简体   繁体   English

为什么我们使用Object作为同步锁?

[英]Why do we use Object as a synchronized lock?

Does it provide any benefit over using lock on String etc? 它是否比使用String等锁定提供任何好处?

private Object lock = new Object();

private String lock = new String();

Any class would do. 任何课程都可以。 Using Object makes sense because it is the smallest and simplest object you can create. 使用Object是有意义的,因为它是您可以创建的最小和最简单的对象。 Anything else would be "too much". 其他任何事情都会“太多”。

Like others have said, there's really no difference between using a String or an Object for your lock, though some would say one is more 'wasteful' of memory than another. 就像其他人所说的那样,对你的锁使用String或Object之间真的没什么区别,尽管有些人会说一个人比另一个更“浪费”内存。 If your looking for some good synchronization 'primitives' though then it's worth taking a look at the Java Concurrency packages , theres actually a Lock object that has alot of useful methods you can utilize. 如果您正在寻找一些良好的同步'原语',那么值得看一下Java Concurrency包 ,实际上是一个Lock对象,它有很多可以使用的有用方法。

Generally you do not want to use String objects as locks for synchronization. 通常,您不希望将String对象用作同步锁。 The reason is that the JVM can optimize memory used for storing Strings by interning them because Strings are immutable. 原因是JVM可以通过实习来优化用于存储字符串的内存,因为字符串是不可变的。 This can potentially cause unrelated parts of your system to 'share' a lock that was never intended to be shared. 这可能会导致系统中不相关的部分“共享”从未打算共享的锁。 This can manifest itself as simply non optimal performance or in the worst case deadlocks from a race condition that is non-obvious without a debugger. 这可以表现为简单的非最佳性能,或者在最坏的情况下,来自竞争条件的死锁,在没有调试器的情况下是非显而易见的。

This also applies for other Object primitive equivalents that are optimized such as Integer, Long, and Boolean. 这也适用于优化的其他Object原语等效项,如Integer,Long和Boolean。 You do not want to use them as locks, as again for example all Boolean objects with the value true could actually be references to the same single instance of Boolean.TRUE. 您不希望将它们用作锁,例如,所有值为true的布尔对象实际上可能是对同一个Boolean.TRUE实例的引用。

This issue is explained further in the link below. 此问题将在下面的链接中进一步解释。

LCK01-J. LCK01-J。 Do not synchronize on objects that may be reused 不要在可能重用的对象上进行同步

No it doesn't. 不,不。 It's just that you explicitly say it's just an Object having no other sense than being used for locking—while String is a string, and an empty String is still a meaningful entity. 只是你明确地说它只是一个没有其他意义的对象,而不是用于锁定 - 而String是一个字符串,而一个空字符串仍然是一个有意义的实体。

No. 没有。

Any object is equally suitable. 任何物体都同样适合。

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

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