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 threaded programming and when is it used? : Java thread
What is Mutex (Mutual Exclusion Object) ?
What are the various access specifiers in java?
Can we access instance variables within static methods ?
What is difference between path and classpath in java?
What is thread life cycle in java?
What is singleton class in ruby?
What are peerless components?
What are the escape sequences in java?
Is a char always 1 byte?
What is method in java with example?
What are the main differences between the java platform and other platforms?
Explain importance of throws keyword in java?
Does string is thread-safe in java?
Is it possible to compare various strings with the help of == operator?