Golgappa.net | Golgappa.org | BagIndia.net | BodyIndia.Com | CabIndia.net | CarsBikes.net | CarsBikes.org | CashIndia.net | ConsumerIndia.net | CookingIndia.net | DataIndia.net | DealIndia.net | EmailIndia.net | FirstTablet.com | FirstTourist.com | ForsaleIndia.net | IndiaBody.Com | IndiaCab.net | IndiaCash.net | IndiaModel.net | KidForum.net | OfficeIndia.net | PaysIndia.com | RestaurantIndia.net | RestaurantsIndia.net | SaleForum.net | SellForum.net | SoldIndia.com | StarIndia.net | TomatoCab.com | TomatoCabs.com | TownIndia.com
Interested to Buy Any Domain ? << Click Here >> for more details...

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 constructor and virtual function? Can we call a virtual function in a constructor?

1083


How do you check whether the list is empty or not in java?

921


Can we increase array size dynamically in java?

897


How many bytes is 255 characters?

923


Can we have try without catch block?

1030


How do you change an int to a string?

947


Is hashmap thread safe?

934


Can we write class inside a class in java?

920


Can we override final method?

941


What are the basic concepts of OOPS in java?

971


Explain what access modifiers can be used for methods?

1030


What is a nullable field?

987


What is ‘is-a ‘ relationship in java?

972


How many bytes is a unicode character?

954


What one should take care of, while serializing the object?

850