I am new to multi-threading in java, and I have a question some might find trivial.
I have to debug a third party piece of code and I need some basic information, to know where to look for the problem because the code is very large.
When the following code runs:
public void method()
{
long startTime = System.currentTimeMillis();
synchronized (obj)
{
log( "time:" + System.currentTimeMillis() - startTime + " ms" );
...
}
}
I get:
11:13:12 - time: 3816 ms...
11:14:14 - time: 0 ms
Why is taking so long (3816 ms) to get the lock for the object? Where should I look? For example, I would imagine a possible answer would be to look for code which acquires the lock for "obj" i.e. block such as:
synchronized (obj) { ... }
Or is it possible that any modification at the object "obj" without "synchronized" can also lock the object?
Aryan Kumar
02-Jul-2023There are a few reasons why it might seem to take a long time for a synchronized block to get a lock.
One possibility is that the object that the synchronized block is locking is being used by another thread. This can happen if the object is being accessed by a method that is also synchronized. In this case, the thread that is trying to acquire the lock will have to wait until the other thread is finished using the object.
Another possibility is that the object that the synchronized block is locking is in a critical section. A critical section is a part of a program where only one thread can be running at a time. This is usually done to prevent race conditions, which are errors that can happen when two or more threads are trying to access the same data at the same time. In this case, the thread that is trying to acquire the lock will have to wait until the other thread is finished with the critical section.
Finally, it is also possible that the object that the synchronized block is locking is in a deadlock. A deadlock is a situation where two or more threads are waiting for each other to release a lock. In this case, the threads will be stuck in a loop and will never be able to acquire the locks that they need.
If you are experiencing long wait times for synchronized blocks, you can try the following:
If you have tried all of these things and you are still experiencing long wait times for synchronized blocks, you may need to consult with a Java expert for help.
Anonymous User
27-Nov-2015