Thread 1: Basically locks global
and does a while loop.
Thread 2: Attempts to get a lock on global
and it it succeeds, proceeds to stop the program.
BUT~ Thread 1 is started first, so technically Thread 2 should never get called and hence the program should never quit.
static Integer global = 30;
public static synchronized void setVar(int x, String from)
{
System.out.println(global + " " + x + " - " + from);
global = x;
}
public static void main(String [] args)
{
Thread thr1 = new Thread(new Runnable()
{
@Override
public void run()
{
synchronized(global)
{
while(true)
{
setVar((int) (Math.random() * 30), "Thread 1");
}
}
}
});
Thread thr2 = new Thread(new Runnable()
{
@Override
public void run()
{
synchronized(global)
{
setVar((int) (Math.random() * 30), "Thread 2");
System.exit(0);
}
}
});
thr1.start();
thr2.start();
}
30 19 - Thread 2
Synchronization can result in hold-wait deadlock where two threads each have the lock of an object, and are trying to acquire the lock of the other thread's object. Synchronization must also be global for a class, and an easy mistake to make is to forget to synchronize a method.
Furthermore, because only one thread can enter into a synchronized block or access a synchronized object, unnecessary use of synchronization can make the application slow. The larger the number of Java threads contending to execute a synchronized block or method, the worse the problem gets.
Synchronization makes sure that shared resources or data can be accessed by only one thread at a time while execution. its advantage is that it prevent data inconsistency and disadvantage is that it makes execution slower as it makes other thread wait till current thread completes execution.
It is perfectly possible for thr1
to start and be parked before it hits synchronized
- then thr2
gets the lock and exits.
My only concern is how (int) (Math.random() * 30)
can evaluate to 19
. Now that is weird.
The number 1 quote for 90% of all thread-related issues: the order of execution with threads is undefined.
In your example:
Thread 1: created, put on hold for whatever reason
Thread 2: created, runs to synchronized and gets lock.
Thread 1: resumed, runs to synchronized, has to wait.
So if you write threaded code that uses such synchronized models, you need to be prepared for all cases, because which one actually happens, no one can say.
Furthermore on your "should never get called". Yes it is unlikely, but even if the chance is at let's say 1%, that still means within 100 runs it will happen statistically at least once.
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