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 importance of throws keyword in java?

776


What is return keyword in java?

822


What is the difference between char and char *?

775


Is passing by reference faster?

769


What do you mean by thread safe?

770


Does java vector allow null?

734


Is simpledateformat safe to use in the multithreaded program?

764


How do you reverse sort in java?

734


What do you understand by soft reference?

823


How can we run a java program without making any object?

779


What are the classes of java?

743


what is enumset?

811


What are different access specifiers in java?

770


Is there any way to skip finally block of exception even if some exception occurs in the exception block?

853


What is the difference between variable & constant?

779