Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ensure Java synchronized locks are taken in order?

we have two threads accessing one list via a synchronized method. Can we

a) rely on the run time to make sure that each of them will receive access to the method based on the order they tried to or

b) does the VM follow any other rules

c) is there a better way to serialize the requests?

like image 473
MrG Avatar asked Nov 26 '09 10:11

MrG


People also ask

How do you lock a class what are the ways to achieve synchronization in Java?

Every class in Java has a unique lock which is nothing but a class level lock. If a thread wants to execute a static synchronized method, then thread requires a class level lock. Once a thread got the class level lock, then it is allowed to execute any static synchronized method of that class.

Which lock is required for synchronized method in Java?

Every class in Java has a unique lock which is nothing but class level lock. If a thread wants to execute a static synchronized method, then the thread requires a class level lock.

What is lock in synchronized Java?

When we use a synchronized block, Java internally uses a monitor, also known as monitor lock or intrinsic lock, to provide synchronization. These monitors are bound to an object; therefore, all synchronized blocks of the same object can have only one thread executing them at the same time.

How can we prevent deadlock synchronization?

Coming to your problem, it will not deadlock. If you have two independent attribute in a class shared by multiple threads, you must synchronized the access to each variable, but there is no problem if one thread is accessing one of the attribute and another thread accessing the other at the same time.


2 Answers

No, synchronized will give access in any order (Depends on the JVM implementation). This could even cause Threads to starve in some scenarios.

You can ensure the order by using ReentrantLock (since Java 5.0) with the fair=true option. (Lock lock = new ReentrantLock(true);)

like image 174
Hardcoded Avatar answered Sep 19 '22 14:09

Hardcoded


No you cannot be sure that two calls to a synchronized method will occur in order. The order is unspecified and implementation dependent.

This is defined in the 17.1 Locks section of the JLS. Notice that is says nothing about the order in which threads waiting on a lock should gain access.

like image 37
Stephen C Avatar answered Sep 16 '22 14:09

Stephen C