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
Which is best ide for java?
Can a class extend more than one class?
What is static in java?
Can we extend singleton class in java?
What does void * mean?
Does java linked list allow duplicates?
Which method must be implemented by all threads?
Which variable is the independent variable?
What is java util concurrentmodificationexception?
What are the important methods of java exception class?
What does exclamation mean in java?
What is t type java?
What happens if an exception is not handled in a program?
What means public static?
What is a marker interface?