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
Is singleton a bad practice?
What is externalizable?
Explain the difference between protected and default access.
Is java owned by oracle?
Can we have multiple classes in single file ?
What exceptions occur during serialization?
What are dot operator queries?
what is the messsage u r going to get from an objectoriented programing?
Does anyone still use java?
What does indexof mean?
What is the exact difference in between unicast and multicast object? Where we will use?
Is c better than java?
Print Vertical traversal of a Binary Tree.
What does 3 dots mean in java?
What are latest features introduced with java 8?