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?
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.
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.
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.
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.
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);
)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With