Sobes.tech
Middle+

How to make a method thread-safe so that it cannot be called from another thread while it is executing in one thread?

sobes.tech AI

Answer from AI

Use the synchronized keyword for the method.

class SafeCounter {
    private int count = 0;

    public synchronized void increment() {
        // This block of code will be executed by only one thread at a time
        count++;
    }

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

You can also use a synchronized block with an object monitor.

class AlternativeSafeCounter {
    private int count = 0;
    private final Object counterLock = new Object(); // Create a monitor object

    public void increment() {
        synchronized (counterLock) { // Synchronize on the counterLock object
            count++;
        }
    }

    public int getCount() {
        synchronized (counterLock) { // Synchronize on the counterLock object
            return count;
        }
    }
}

Other mechanisms for more complex synchronization:

  • ReentrantLock: A more flexible alternative to synchronized with the ability to get lock information and manage timeouts.
  • Semaphore: Limits the number of threads that can access a resource simultaneously.
  • Atomic classes (e.g., AtomicInteger): Provide atomic operations on primitive types without explicit locking.

Example with AtomicInteger:

import java.util.concurrent.atomic.AtomicInteger;

class AtomicCounter {
    private final AtomicInteger count = new AtomicInteger(0);

    public void increment() {
        count.incrementAndGet(); // Atomic increment operation
    }

    public int getCount() {
        return count.get();
    }
}
How to make a method thread-safe so that it cannot be… - sobes.tech