Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which thread will get the lock?

suppose we have multi processor machine and multi threaded application. If two threads have access to a synchronized method and they got executed at the same time which thread will gets the lock? or what will happen?

Thanks

like image 959
Feras Odeh Avatar asked Oct 17 '10 10:10

Feras Odeh


2 Answers

The behaviour will be non-deterministic (that is, either thread may get the lock), and it may vary from execution to execution. This is because it depends on the specific JVM implementation, and the particular scheduling of your threads.

According to this article the JVM specification puts no restrictions on fairness:

Fairness
The Java memory model does not specify any fairness requirement for threads or preemptive multi-threading. A thread can refuse to surrender the CPU to another thread and throw the system into deadlock. The rules for fairness to other threads are defined by the individual JVM implementations.

That is, unless you carefully synchronize your program, one thread may theoretically get starved by the scheduler.

like image 138
aioobe Avatar answered Nov 14 '22 15:11

aioobe


The point is that there is no such thing as "at the same time". One of the two will get the lock, but you have no way to know which one.

There is no such thing "at at the same time" because, liberally speaking, a lock is something that chooses and executes the threads one at a time exclusively.

This is naturally accomplished in a pure monoprocessor system that can execute one instruction at a time. On multiprocessor systems usually there is some hardware device that "locks" the processors to prevent them from executing at the same time.

like image 20
IlDan Avatar answered Nov 14 '22 16:11

IlDan