How would you ensure that a shared resource is accessed safely by multiple threads?

To let multiple threads safely access a shared resource, Java provides synchronization, which restricts access to a critical section of code so only one thread can execute it — and therefore modify the shared state — at any given time.

Key Points

Example

A shared inventory counter updated by multiple order-processing threads can be protected by wrapping the decrement operation in a synchronized block on the inventory object, ensuring two threads never simultaneously read and decrement the same stale count.

public synchronized void decrementStock(int qty) {
    if (stock >= qty) {
        stock -= qty;
    }
}

Interview Tip

A concise interview answer is

I'd use synchronization — either a synchronized method or block — around the critical section that touches the shared resource, so only one thread can execute it at a time. That prevents race conditions from multiple threads reading and modifying the same state concurrently.

Last updated: 16 July 2026

Next question: Explain the synchronized keyword in Java. How does it work?

More Concurrency and Multithreading interview questions

All Concurrency and Multithreading questions