Assigning an object in a synchronized block based on this object (Java)

I came across some (production!) Code that looks like a snippet below:

synchronized(some_object) {
    some_object = new some_object()
}

I expect this to be subject to all kinds of terrible race conditions, and that a second thread can enter this block, creating a new object. My Java chops are not good enough to finally formulate the expected behavior above, so it is curious what you have to say before I reorganize this.

+5
source share
4 answers

As Francis says, this is not a problem. Your snippet is equivalent to this:

SomeObject saved = some_object;
synchronized(saved) {
  some_object = new SomeObject()
}
+2
source

, , . . , some_object . , , .

.

+4

, . . - "" .

+1

. .

A modern approach to creating an object in thread safe mode uses the AtomicReference compareAndSet in a loop, as described in Goetz Java Concurrency in action (chapter 15). This does not block your threads and provides much greater performance than a synchronized block.

private final AtomicReference<SomeObject> someObject = new AtomicReference<>();


void buildIt() {
   SomeObject obj = new SomeObject();
   SomeObject current = someObject.get();  //probably null, but doesn't matter
   while (true) {
      if (someObject.compareAndSet(current, obj)) 
          break;
   }
}
+1
source

All Articles