Johan Johan - 7 months ago 28
Java Question

which are thread-safe methods among wait(), notify(), lock(), unlock(), await(), signal(), acquire() and release()

I am new to Java multithreading and I would like to see If I am reasoning well.

From my understanding,

wait()
and
notify()
are NOT thread-safe methods (inherited from class
Object
) and for this reason, in order they to work correctly, any design expects them to be within synchronized blocks.

On the other hand,
lock()
and
unlock()
from
ReentrantLock()
class,
await()
and
signal()
from
ReentrantLock.Condition
class,
acquire()
and
release()
from
Semaphore
seem to be more high level constructs designed to be used without need of synchronized blocks. As far as I expect, this should be possible just because all these methods are natively thread-safe.

This is correct?

**EDIT: ** if object
obj
is accessed by different threads via
obj.x()
, then
obj.x()
is thread-safe if different threads can't interleave while executing it; so if a thread starts executing
obj.x()
, this call is atomic and any other thread will be put on hold for executing that method.

Answer

None of the methods that you've enumerated are synchronized or use synchronized blocks. Nevertheless they were all meant to be called in a multithreaded environment, so they provide the means to do this safely.

All of these methods except Condition.await() and Condition.signal() can be used without any locks being held.

  • await() and signal() are roughly equivalents to Object.wait() and Object.notify(), so for practically all JDK implementations of the Condition interface, you'll need to hold the lock associated with the condition variable.

All of these methods rely on a fundamental building block for the java.util.concurrent package called AbstractQueuedSynchronizer. It's a pretty elaborate thing (there's a whitepaper for it) that can provide the functionality of the synchronized methods or blocks plus some additional goodies.

P.S. I assume you meant Semaphore.release() instead of Semaphore.signal().