forum

Home / DeveloperSection / Forums / Why does it seem to take a long time for this synchronized block to get a lock?

Why does it seem to take a long time for this synchronized block to get a lock?

Anonymous User 1459 27-Nov-2015
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?

Updated on 02-Jul-2023
I am a content writter !

Can you answer this question?


Answer

2 Answers

Liked By