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 importance of throws keyword in java?
What is return keyword in java?
What is the difference between char and char *?
Is passing by reference faster?
What do you mean by thread safe?
Does java vector allow null?
Is simpledateformat safe to use in the multithreaded program?
How do you reverse sort in java?
What do you understand by soft reference?
How can we run a java program without making any object?
What are the classes of java?
what is enumset?
What are different access specifiers in java?
Is there any way to skip finally block of exception even if some exception occurs in the exception block?
What is the difference between variable & constant?