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