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
How objects of a class are created if no constructor is defined in the class?
What is the difference between a choice and a list?
What is anagram number?
What is the difference between an array and an array list?
What are internal variables?
What are recursive functions? Give some examples?
Howto get an object that will perform date & time calculations then format it for output in some different locales with different date style.can ne1 tel me the answer of this question.pls
What is data string?
Can we convert list to set in java?
What are class members by default?
Define array. Tell me about 2-D array.
What is a jit compiler?
How to display all the prime numbers between 1 and 100
What is == mean?
Explain about automatic type conversion in java?