0

I'm working on a small game to be played through discord by me and some friends.

My code should theoretically work, but for some reason I can't escape the IllegalMonitorStateException "current Thread is not owner" caused by the wait() method below.

public void waitForMethod () { Thread thread = new Thread() { @Override public void run () { synchronized(lock) { while (true) { if (methodDone) { methodDone = false; channel.sendMessage("methodDone = true").queue(); break; } else { channel.sendMessage("methodDone = false").queue(); try { wait(); channel.sendMessage("successfully notified.").queue(); } catch (InterruptedException e) {} } } } } }; thread.run(); channel.sendMessage("exited Thread.").queue(); } 

So far, I've been able to get all but the "successfully notified" message and "methodDone = true" to send, obviously because as soon as it calls "wait();" it raises the IllegelMonitorStateException "current Thread is not owner."

Below is the code that relies on the "waitForMethod()" method.

@Override public void onMessageReceived (MessageReceivedEvent event) { synchronized(lock) { handleEvent(event); lock.notify(); } } 

To be clear, waitForMethod is called by a class that represents the game's loop, and is simply meant to make the game loop pause until a variable has been changed by the "handleEvent()" method to true, in which case it should continue the game's loop.

I'm basically just looking for a way to pause a section of code until another section of code tells it to unpause.

I tried using the EventWaiter, but I couldn't find a way to properly set up the dependencies or import it, so I kind of gave up and went with something I'm at least somewhat familiar with.

3
  • 1
    Call lock.wait() instead of wait() Commented Jun 30, 2024 at 9:08
  • FYI: wait() is shorthand for writing this.wait() If this was the object that the other thread was going to notify (which, in your case, it isn't) then the unadorned wait() call would work inside of a synchronized(this) block. Commented Jun 30, 2024 at 20:31
  • 2
    Also note: Your method calls wait() if the condition has not been met. As a matter of good hygiene, you should always call it while the condition is not met. This comment box is too small for me to explain why, but you should never rely on the condition being satisfied when wait() returns. You should always re-check it, and wait() again if necessary. Commented Jun 30, 2024 at 20:37

1 Answer 1

1

Replace wait(); with lock.wait(); in waitForMethod.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.