8

Hello there good poeple, I need some help.

I'm writing a music player which streams music from the web. If I pres the play button before the music is done buffering I want it to wait.

I tried doing something like this:

Object mutex = new Object();

public void main() {
    startStreaming();
    mutex.notify();
}

private void onClickPlayButton() {
    mutex.wait();
}

The problem is that is the playButton is not pressed the mutex.notify() if throws a "llegalMonitorStateException". How do you normally solve problems like this?

EDIT To make clear. My question is: How do I make the button wait for the "startStreamning" method to finish?

Martin Hansen
  • 571
  • 4
  • 8
  • 14
  • 1
    this might help (see accepted answer)... http://stackoverflow.com/questions/5291041/is-there-a-mutex-in-java – Ahmed Kotb May 19 '11 at 18:46
  • Do you really need a mutex for this? I doubt you want to block the UI thread while the download finishes. I would think you could accomplish "don't play yet" by just checking a flag for `isDownloadComplete()` – matt b May 19 '11 at 19:02

7 Answers7

11

According to the JavaDoc,

IllegalMonitorStateException is thrown "to indicate that a thread has attempted to wait on an object's monitor or to notify other threads waiting on an object's monitor without owning the specified monitor."

In order to call mutex.wait() or mutex.notify(), the calling thread must own a lock on object mutex.

This exception is thrown if you call it without a preceding synchronized (mutex) { }

Check out the nice animation of wait and notify in this link : How do wait and notify really work?

Saurabh Gokhale
  • 53,625
  • 36
  • 139
  • 164
5

for wait(), notify() call, you need a synchronized code. try this:

synchronized (this) {
  try {
    this.wait();
   } catch (InterruptedException e) {
     e.printStackTrace();
   }
}


synchronized (this) {
   notify();
}
Erhan Bagdemir
  • 5,231
  • 6
  • 34
  • 40
4

Try use Semaphore with 0 initial permit. Semaphore mutex = new Semaphore(0);

in main mutex.release();

in on click mutex.acquire();

Mikita Belahlazau
  • 15,326
  • 2
  • 38
  • 43
2

from javadoc wait This method should only be called by a thread that is the owner of this object's monitor and for notify This method should only be called by a thread that is the owner of this object's monitor.

this means htat you have to synchronize using the mutex when using notify and wait

anfy2002us
  • 683
  • 1
  • 7
  • 15
0

You have to wait before you notify.

Charlie Martin
  • 110,348
  • 25
  • 193
  • 263
0

You have to synchronize on the mutex to call notify and wait

AdrianRM
  • 2,622
  • 2
  • 25
  • 42
0

You can either look at using more complex lock objects, or simply munch the exception in a try/catch block. The later is definitely "quick and dirty".

For a more advance locking objects, take a look at http://download.oracle.com/javase/tutorial/essential/concurrency/newlocks.html

Taylor
  • 3,942
  • 2
  • 20
  • 33