Forums Register Login

wait() without notify()/notifyAll()

+Pie Number of slices to send: Send
i have a doubt relating wait()/notify()

Its said ,wait() without notify() is uselss.
I tried ,
1. It gave error ,illegalMonitorStateException .Is it because of missing notify() or some other error.
2. Will wait() keep on waiting indefinitly, without notify() unless some external /JVM interrupt comes. or wait() in such case doesnt work.
Thnks
+Pie Number of slices to send: Send
 

Its said ,wait() without notify() is uselss.



This is not true. I have seen cases of applications that use the timeout version of the wait() method -- to force the sleeping of a thread, without the synchronization lock.


1. It gave error ,illegalMonitorStateException .Is it because of missing notify() or some other error.
2. Will wait() keep on waiting indefinitly, without notify() unless some external /JVM interrupt comes. or wait() in such case doesnt work.
Thnks



1. No. You got an illegal state exception because you didn't own the lock of the object that you are trying to wait on.
2. wait() will wait until it gets a notification or interruption.

Henry
+Pie Number of slices to send: Send
Threads do a notify (notify all ???) on themselves when the exit so you could implement a join by using wait without a notify .....

This worked (look no notify!) ...

<code>
Thread t = new Thread (new Runnable() { public void run () { try{Thread.sleep (10000);}catch(InterruptedException e){}} });
t.start();

synchronized (t) {try{t.wait();}catch(InterruptedException e){}}
</code>
+Pie Number of slices to send: Send
But Chris, it's possible for thread t to run and complete before the synchronized block starts. In that case, wait() will wait forever. Also, I believe that the fact that the system calls notifyAll() on an exiting thread is undocumented, and in theory it could change in a future release (though I doubt it ever will). It's unreliable to rely on undocumented features. However, for current implementations, you could probably replace a join with

Of course there's little reason to actually do this other than to test how join() works.
+Pie Number of slices to send: Send
I was very aware when I typed that there was a race condition albeit theoretical hence I should've the wait so high and yes I should have commented it as such ;-)

As for the undocumented feature very interested in that i.e. I just read that happened else where and took it as gospel , I'm trying to read the Java language specs to get detail. I thought the book I read said that always happened but it may well have said 'might' and I just gloss'ed over,
I thought it was tied into the whole variable caching thread issues e.g. JSR 133 type stuff, if I can find the origonal source I'll let you know.

Why is it open ended I'ed have no problem with it always calling notify or never but to leave it open ended seems dangerous .... OS dependant issues ???
+Pie Number of slices to send: Send
 

Originally posted by Lucky J Verma:
i have a doubt relating wait()/notify()

Its said ,wait() without notify() is uselss.
I tried ,
1. It gave error ,illegalMonitorStateException .Is it because of missing notify() or some other error.
2. Will wait() keep on waiting indefinitly, without notify() unless some external /JVM interrupt comes. or wait() in such case doesnt work.
Thnks



The reason for 1 might be you have not called wait after acquiring a lock.
The reason for 2 is that it will keep on waiting it you do not call parameterized wait , which takes a timeout.
+Pie Number of slices to send: Send
I thought wait() and notify()/notifyAll() had to be called from within a synchronized method.
Part of wait's functionality is to release it's current lock and suspend itself. If there is no lock when it is called that might give a "state" related error.
+Pie Number of slices to send: Send
 

Originally posted by Bob Ruth:
I thought wait() and notify()/notifyAll() had to be called from within a synchronized method.


Why would they need to be ?

(Actually, I am not dis-agreeing nor positing that they shouldn't be - it's just that there should be a reason for something so the system designer can make informed trade-offs)
+Pie Number of slices to send: Send
[Bob]: I thought wait() and notify()/notifyAll() had to be called from within a synchronized method.

There must be a a synchronized block or method involved. You don't necessarily have to be within that block or method, if inside the block or method there was a call to another method. For example:

If you call method a(), the call to b() will not cause an IllegalMonitorStateException, because the lock on "this" was acquired at the beginning of method a(), and it will not be relinquished until the end of a(). So the current thread has the lock on "this" while b() executes. However if b() is called directly (without calling a()), then it will throw an IllegalMonitorStateException. Unless there's some additinoal synchronization code, not shown. For that reason, method b() should be made private, to prevent outside code from invoking wait() without the appropriate lock.

[Bob]: Part of wait's functionality is to release it's current lock and suspend itself. If there is no lock when it is called that might give a "state" related error.

[Nicholas]: Why would they need to be ?

Well, this isn't hypothetical - you do need to use synchronization to call wait(), or you will get an IllegalMonitorStateException. As for why - well, Bob's answer is part of it.

But more generally, the basic intent of wait() is that you want a thread to wait for some event. What that event is, it's up to you to code. You wait for a notify(), at the very least, but for various reasons it's not enough to just wait for notify. A notify is like a tap on the shoulder saying "something happened". But you need to check after the notify - what happened, and was it the thing you were waiting for? Maybe you were waiting for a boolean variable to turn true, or for an int value to reach 0, or any number of other possible things you might imagine.

What these things have in common is: they all involve changes in some data, somewhere, and that data is being manipulated or accessed by more than one thread. And any time you have changeable data accessed by more than one thread, you need some sort of protection in order to make it safe - by using synchronization, transient, or java.util.concurrent.locks classes.

Back when they originally designed wait(), transient wasn't very effective, and java.util.concurrent wasn't around. So they chose to give programmers some extra encouragement to do what they really should have been doing anyway: use synchronization to protect the integrity of the data being accessed. It's a form of extra run-time checking to catch a common source of errors.
+Pie Number of slices to send: Send
Where are these Monitor objects, which govern the throwing of IllegalMonitorStateException's discussed ?

They are not discussed at:

Class Object is the root of the class hierarchy

I can see where the void wait(long timeout) could be used but have not been able to find any substantive docs on monitors and it's first time for "transient wasn't very effective" I have come to label all class vars as transient, but did not know this keyword had anything to do with Java � Threads and Synchronization. Additionally, if the JVM can interrupt a wait(), due to some external condition such as ( ??? ), it would solve my "How do you monitor whether the operator wants to break off the session without throwing a ....." question.

I had been grappling with this since November, trying to figure out how to do this without programming by Exception.
+Pie Number of slices to send: Send
Re: "transient wasn't very effective" - sorry, I meant volatile, not transient. Transient has nothing to do with threads; I just sometimes say one when I mean the other. Anyway, prior to the new memory model (as of JDK 5) volatile had somewhat weaker semantics and was harder to use effectively. It's still somewhat difficult to use for anything but very simple cases.

Monitors are mentioned numerous times in the Object API, including the descriptions for the wait() and notify() methods. The term is actually defined in the JLS here. Basically a monitor is the part of an Object that knows whether that object is locked (via synchronization) or not. Often we use these terms somewhat interchangeably. Informally, all these expressions mean the same thing, as used by most Java programmers

lock object x
lock object x's monitor
acquire a lock on x
synchronize on x
sync on x's monitor
acquire x's lock
(and various other similar permutations)

and they all correspond to what happens when this code is executed:


[Nicholas]: Additionally, if the JVM can interrupt a wait(), due to some external condition such as ( ??? ),

It can. See this reference to spurious wake-ups in the JLS.
+Pie Number of slices to send: Send
 

Why would they need to be ?



I would like to address the question of "why" a bit more...

First, this is *not* a Java issue -- the designers of Java didn't just invent the wait/notify mechanism. If you examine the condition variable support of the Solaris threads library, POSIX threads library, or even Windows threads library, the all require that a mutex (lock/monitor) be held during the waiting call, and they all will release and reacquire the lock during the call.

Why? it is because every single other threading library does it.


As for why all thread libraries does it, Jim explained most of it. It is because the condition variable is signalling a condition, that is tied to a state variable, that must be shared between threads. To further elaborate, it is also that it can't be done outside of the wait() method -- there is a really subtle race condition.

In the simple case, let's have one thread wait for all notifications. This thread grabs the lock, does some work, and goes back to a waiting state. If for example, the CV didn't require the mutex, but the thread must wakeup, grab the lock, do the work, release the lock, and then go back to a wait state. It will be possible for a second notification to be sent, in between the wakeup, and the lock grab -- hence, a notification will be lost.

Condition Variables not only release and reacquire locks, they also go into and out of the cooresponding wait state, in an atomic fashion, so that notifications will not be lost. (It is still possible to lose notification if the locks are released manually, via leaving a block, but not if all releases and reacquires are done with wait()). This is why the wait() mechanism must own the lock -- because it will not be possible for an additional method call to release the lock atomically.


As for notify, there is no reason for that. In fact, I am not sure if any of the other threading libraries require it. I guess Java does it to be consistent.


BTW, for the purpose of this post, I am using lock, mutex, and monitor, interchangeably.

Henry
[ June 18, 2007: Message edited by: Henry Wong ]
+Pie Number of slices to send: Send
[JY:]Re: "transient wasn't very effective" - sorry, I meant volatile, not transient.
I was sure this is what you meant, obbvious from the context - mention was for the benefit of other posters.
17.8.4: The above specifications allow us to determine several properties having to do with the interaction of waits, notification and interruption. If a thread is both notified and interrupted while waiting, it may either:
  • return normally from wait, while still having a pending interrupt (in other works, a call to Thread.interrupted would return true)
  • return from wait by throwing an InterruptedException

  • Java Standard Edition 7 ("Dolphin") is expected to implement escape analysis and related optimizations. This could, and likely would, introduce intractable challenges for the source-coder for which detailed analysis and contemplation is ineffective for resolving 17.8.4 This is (in it's net effect) (in my opinion) a candidate for a JSR - any Syntactic ambiguity would be inconsistent with the remarkable wealth of cs going on in Java.

    May I suggest 17.8.4 is a generalization which will produce wrong code from baccalaureate cs's ? I note one institution requires: "At least 3 years of industrial experience in the programming field." This is really getting interesting, the field shipping to adademia, rather than the traditional approach.

    +Pie Number of slices to send: Send
     

    Java Standard Edition 7 ("Dolphin") is expected to implement escape analysis and related optimizations. This could, and likely would, introduce intractable challenges for the source-coder for which detailed analysis and contemplation is ineffective for resolving 17.8.4 This is (in it's net effect) (in my opinion) a candidate for a JSR - any Syntactic ambiguity would be inconsistent with the remarkable wealth of cs going on in Java.



    Actually, I believe "escape analysis" have been implemented with Java 6. Of course, by Java 7, I would not be surprised if much more optimizations will be added.

    BTW, "escape analysis" actually affect many things -- the coolest is probably the ability to allocate objects on the stack instead of the heap. However, the nice thing about these optimizations is that the Java developer doesn't really need to know or care.

    In the area of threads, the JVM will just *not* synchronize a method or block, even if the method or block is synchcronized. This is actually not a problem. If an object can't escape a method call, it will not be shared between threads anyway.

    Henry
    +Pie Number of slices to send: Send
    Henry; before somebody hammers me on fine points, let me disambiguate that Java is developing quickly a body of linguistic that is rich with things one can do - O.P.'s question involved Its said ,wait() without notify() is uselss. Your reply is one of the detailed attention to issues that threading requires and was an attempt by me to thwart .... such case doesn't work. because of issues I had not considered.
    I see you are having a nice day:
    77�F
    Clear
    Wind: N at 4 mph
    Humidity: 58%


    [ message edit: what about this ?]



    [ June 18, 2007: Message edited by: Nicholas Jordan ]
    [ June 23, 2007: Message edited by: Nicholas Jordan ]
    +Pie Number of slices to send: Send
    Henry, I totally missed the "address the question of "why" a bit more..."
    I think it went up while I was drafting the other response.
    Comments are in order:
  • First, this is *not* a Java issue Well, Java is taking a pretty wide swath across computer science and has taken a forefront role in the WWW, which is taken over quite a bit of the social structure in a hurry. If the machine can fail because of threading issues, I take the position that we should examine the matter carefully.
  • because every single other threading library does it Surely there must be a way of programing without exceptions. (?)
  • there is a really subtle race condition Sorry, I have to deal with these all day long (really subtle race condition), under great risk and stress. I realize the matter is subtle, perhaps gossamer in it's more tangible manifestations and seemingly beyond the scope of Java. I immediately recognized the subtle race condition and sought to learn how to prevent it from becoming a problem later on.


  • [ June 18, 2007: Message edited by: Nicholas Jordan ]
    [ June 23, 2007: Message edited by: Nicholas Jordan ]
    +Pie Number of slices to send: Send
    [Henry]: First, this is *not* a Java issue

    Nicholas, I believe Henry is saying it's not just a Java issue. In my last post I made it sound like this was just something Java's designers did; Henry is correctly pointing out that it's a common paradigm in a number of other languages too, and often rooted in underlying system libraries.

    [Nicholas]: Surely there must be a way of programing without exceptions.

    Yes, other ways are possible, but using exceptions is a fairly common technique in Java, and it's what Sun's engineers chose to do here.

    [Nicholas]: [ message edit: what about this ?]

    What about it? Does it have something to do with the subject of this thread? Other than having to do with threads and synchronization, which after all is what the whole forum is for? I suggest if you want to open a new topic, it might make sense to start a new discussion thread.
    +Pie Number of slices to send: Send
    [JY:]What about it?   That would be a new topic, I stand corrected.

    [JY:]using exceptions is a fairly common technique in Java
      Well, in my opinion the Java engineers need to revisit the issue.

    [JY:]Henry is saying it's not just a Java issue   There are subtle differences between your mind and Master Wong - as noted in recent post in M.D.
    +Pie Number of slices to send: Send
     

    [JY:]Henry is saying it's not just a Java issue -- There are subtle differences between your mind and Master Wong - as noted in recent post in M.D.




    Maybe. But in this regard, I am in agreement with Jim.

    Henry
    Those cherries would go best on cherry cheesecake. Don't put those cherries on this tiny ad:
    a bit of art, as a gift, that will fit in a stocking
    https://gardener-gift.com


    reply
    reply
    This thread has been viewed 4128 times.
    Similar Threads
    K&B: Question on Threads-Selftest.
    Consuming no CPU cycles
    Cleared SCJP 6
    Determine whether object's lock is held
    Core Java Question
    wait() and notify() question...
    Wait Method
    thread
    More...

    All times above are in ranch (not your local) time.
    The current ranch time is
    Mar 29, 2024 05:19:39.