Course Content
Keywords
Operators
Loops
String
Array
Object Oriented Principle
Memory Management
Collection Framework
Exception Handling
Reflection API
Multi Threading
File Handling
Java Version wise Questions
Java Scenario Based Interview Questions
About Lesson
Scenario: You’re working with a shared int variable in a multithreaded environment. Multiple threads need to increment the value of the int variable. What issues can arise, and how would you ensure thread safety?

 

Answer:

 

When multiple threads try to increment the same int variable, a race condition can occur. Without synchronization, two threads might read the same value before incrementing it, leading to lost updates. The solution is to use synchronization or atomic variables.

You can use synchronized blocks to ensure that only one thread can access the int variable at a time:

 


class Counter {
    private int count = 0;

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

    public int getCount() {
        return count;
    }
}

 

Alternatively, you can use AtomicInteger from the java.util.concurrent.atomic package, which provides thread-safe operations on integers:

 

import java.util.concurrent.atomic.AtomicInteger;

class Counter {
    private AtomicInteger count = new AtomicInteger(0);

    public void increment() {
        count.incrementAndGet();
    }

    public int getCount() {
        return count.get();
    }
}