How to make a method thread safe without using synchronized
keyword?
Answer Posted / isak
Use ReentrantLock which belongs to java.util.concurrent.locks.ReentrantLock package
Below is the method printCount() which has synchronised without using synchronised.
Lock lock = new ReentrantLock();
public void printCount(String threadName){
lock.lock();
try {
for(int i = 5; i > 0; i--) {
System.out.println("Counter --- " + i +" With thread : "+threadName);
}
} catch (Exception e) {
System.out.println("Thread interrupted.");
}finally{
lock.unlock();
}
}
| Is This Answer Correct ? | 3 Yes | 0 No |
Post New Answer View All Answers
What is constructor and virtual function? Can we call a virtual function in a constructor?
How do you check whether the list is empty or not in java?
Can we increase array size dynamically in java?
How many bytes is 255 characters?
Can we have try without catch block?
How do you change an int to a string?
Is hashmap thread safe?
Can we write class inside a class in java?
Can we override final method?
What are the basic concepts of OOPS in java?
Explain what access modifiers can be used for methods?
What is a nullable field?
What is ‘is-a ‘ relationship in java?
How many bytes is a unicode character?
What one should take care of, while serializing the object?