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
Explain about arraylist?
Which programming language is most secure?
What are the features in java?
In java, what is the difference between method overloading and method overriding?
What is a ?
what is mutual exclusion? : Java thread
What are the advantages of arraylist over arrays?
What is core java used for?
How do you remove duplicates from an array in java?
Can a set contain duplicates?
What is method reference?
What do you understand by the term string pool?
What is java in detail?
What is foreach loop in java?
What is the difference between multitasking and multithreading in Java