Sobes.tech
Junior — Middle

What are other ways to implement thread synchronization besides using the synchronized keyword?

sobes.tech AI

Answer from AI

In addition to the synchronized keyword in Java, there are several other ways to synchronize threads:

  • ReentrantLock from the java.util.concurrent.locks package — a more flexible alternative to synchronized with the ability to interrupt lock waiting and attempt to acquire with a timeout.

  • Semaphore — limits the number of threads that can access a resource simultaneously.

  • CountDownLatch and CyclicBarrier — allow coordinating the execution of multiple threads by waiting for certain events to occur.

  • Atomic classes (AtomicInteger, AtomicReference, etc.) — provide atomic operations without explicit locking.

  • Volatile — guarantees visibility of variable changes between threads but does not ensure atomicity.

Example of using ReentrantLock:

import java.util.concurrent.locks.ReentrantLock;

ReentrantLock lock = new ReentrantLock();

lock.lock();
try {
    // critical section
} finally {
    lock.unlock();
}
What are other ways to implement thread… - sobes.tech