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


Please Help Members By Posting Answers For Below Questions

Explain about arraylist?

571


Which programming language is most secure?

519


What are the features in java?

572


In java, what is the difference between method overloading and method overriding?

576


What is a ?

745






what is mutual exclusion? : Java thread

550


What are the advantages of arraylist over arrays?

559


What is core java used for?

503


How do you remove duplicates from an array in java?

524


Can a set contain duplicates?

513


What is method reference?

511


What do you understand by the term string pool?

559


What is java in detail?

553


What is foreach loop in java?

524


What is the difference between multitasking and multithreading in Java

715