简体   繁体   中英

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? 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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