简体   繁体   English

我可以在Java中的同步块之外的共享字段上检查null吗?

[英]Can I check for null on a shared field outside of a synchronized block in java?

Let's say I have a field that can be accessed by two separate threads. 假设我有一个可由两个单独的线程访问的字段。 I'm using an Object for the synchronization lock. 我正在使用对象进行同步锁定。 Can I check for null outside of the synchronization block? 是否可以在同步块之外检查null In other words, is this thread-safe: 换句话说,这是线程安全的:

private Object sharedObject() = new Object();
private final Object sharedObjectLock() = new Object();

private void awesomeMethod() {
   if(sharedObject != null) {
      synchronized(sharedObjectLock) {
         //code the uses sharedObject
      }
   }
}

No, it's not thread-safe. 不,它不是线程安全的。 If another thread nullifies sharedObject field, your thread is not guaranteed to see that change. 如果另一个线程使sharedObject字段无效,则不能保证您的线程看到该更改。

No. The assignment of the variable could occur after you check but before you get the lock. 否。在检查之后但在获得锁之前,可能会发生变量的分配。

There was, at one time, a school of thought that synchronized locks were expensive, but that's not true anymore. 曾经有一种思想认为同步锁很昂贵,但是现在已经不对了。 Just grab the lock. 只要抓住锁。

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

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