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
Can a string be null?
What is import java util arraylist?
What is Major and importance difference between for and foreach loop ?
Which class is the superclass of all classes?
Explain about oops concepts.
Define how objects are stored in java?
What are the different data types in java?
Can we have static methods in an interface?
What is the meaning of variables in research?
Difference between static and dynamic class loading.
Explain spliterator in java8?
What is object-oriented programming?
How many unicode characters are there?
What does singleton mean in java?
Is array a class?