Java.lang.IllegalMonitorStateException: object is not locked by the thread before waiting ()

But I synchronize the list object wherever it becomes new. Why?

Violation Code:

public Roster getRoster() { if (roster == null) { return null; } if (!roster.rosterInitialized) { try { synchronized (roster) { roster.reload(); long waitTime = SmackConfiguration.getPacketReplyTimeout(); long start = System.currentTimeMillis(); while (!roster.rosterInitialized) { if (waitTime <= 0) { break; } roster.wait(waitTime); long now = System.currentTimeMillis(); waitTime -= now - start; start = now; } } } catch (InterruptedException ie) { // Ignore. } } return roster; } 
+6
source share
1 answer

With "gets new," do you mean that you are creating a new registry object?

Are you sure you are synchronized correctly? Synchronization occurs on instances, but not on variables. So if you, for example,

 synchronized(roster) { roster = new Roster(); // do something } 

Then you only synchronized with the old, and not with the new roster .

Thus, the following code should produce the same error:

 Roster roster = new Roster(); Roster othervariable = roster; synchronized(othervariable) { roster = new Roster(); // create a new roster othervariable.wait(1000); // OK, since synchronized with this instance! roster.wait(1000); // NOT OK, not synchronized with *new* roster! } 

Synchronization does not occur with the variable name, but in the content. If you overwrite the contents, you will not be re-synchronized with the new value!

+8
source

Source: https://habr.com/ru/post/915920/


All Articles