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

What is threaded programming and when is it used? : Java thread

804


What is Mutex (Mutual Exclusion Object) ?

892


What are the various access specifiers in java?

798


Can we access instance variables within static methods ?

862


What is difference between path and classpath in java?

735


What is thread life cycle in java?

846


What is singleton class in ruby?

827


What are peerless components?

873


What are the escape sequences in java?

792


Is a char always 1 byte?

761


What is method in java with example?

728


What are the main differences between the java platform and other platforms?

799


Explain importance of throws keyword in java?

794


Does string is thread-safe in java?

832


Is it possible to compare various strings with the help of == operator?

790