Sobes.tech
Junior — Middle

What tools or classes from standard libraries have you used for thread synchronization?

sobes.tech AI

Answer from AI

In Java, the following standard library tools are often used for thread synchronization:

  • The keyword synchronized — blocks access to code or objects, providing exclusive access.

  • Classes from the java.util.concurrent package:

    • ReentrantLock — a more flexible alternative to synchronized with the ability to attempt to acquire the lock and timeout.
    • CountDownLatch, CyclicBarrier — for coordinating multiple threads.
    • Semaphore — to limit the number of threads executing a certain section of code simultaneously.

Example of using synchronized:

public class Counter {
    private int count = 0;

    public synchronized void increment() {
        count++;
    }

    public synchronized int getCount() {
        return count;
    }
}