Object.wait() & Object.notify() method

Hi all,
My question is related to Object.wait() and Object.notify() method which are used by threads. Why these method belongs to Object class and not Thread when they only use by threads ???

This question represents one of the fundamental concepts of multi-threading as implemented in the Java environment. It is worth clarifying and explaining why probably was this decision mandatory for the language designers. The multi-threading capabilities are built-into the Java language and not external built or imposed to the libraries. What this means that every object that can be instantiated and operated upon by the Java Virtual Machine must be able to possess this behaviour.
As far as the Thread class itself is concerned, it provides the ability for the Java objects to be treated as being capable of supporting the re-entrant behaviour. When the object resources are being used by multiple threads produced by the re-entrant-capable process i.e. object, each of these threads are competing. The Java environment handle the competition on the object resources by these threads by providing the monitor mechanism, similar to the semaphors in other languages. While the monitors are being acquired or released for implementing the synchronization, the threads enter into the waiting pool, internal to the Java environment. In this scenario, it is clear, that unless the methods can be "invoked" on the objects being monitored, the threads will fail any synchronization.
The notify() method will allow a given object to be able to wake up a single thread that is waiting on this object's monitor. Similarly, the wait() method allow the given object to cause current thread to wait until another thread invokes the notify() method for this object. Thus, the wait() or notify() methods represent multi-threading capabilities that Java environment implicitly assumes to be the characteristics of every instantiable Java object. The simple semantics of the Object Orientation suggests us that for this to be cleanly and unambiguously implemented, the "ultimate" superclass or root class of the class hierarchy must include these methods in its interface. This way, it becomes easily possible to "inherit" the multi-threading capabilities down to the Java libraries and all Java custom objects.
Finally, should these methods be included in the interface in the Thread class, every object desirous of possessing these capabilities must "sub-class" the Thread class, which means that the custom objects that need to be multi-threaded must be extended from the Thread class and that the Runnable interface will put up no value. This will defy all the notions of building up an object-oriented Java application with correct object inheritance.

Similar Messages

  • Wait and notify in Object

    Hi,
    Who can give me a short java code segment to show the method wait and notify of the class Object.
    I've already tryed as forlow:
    try {
    A a = new A();
    a.wait() ;
    catch (InterruptedException ex) {
    ex.printStackTrace() ;
    But a thread is always be thrown:
    java.lang.IllegalMonitorStateException: current thread not owner
         at java.lang.Object.wait(Native Method)
         at java.lang.Object.wait(Object.java:420)
         at A.main(A.java:34)
    Who can tell which thread should be the owner thread? I did realize noly one thread there.
    Thanks a million.

    The classic example is two threads, on adding items to a queue and one taking them off and processing them:
    // consumer
    Object item = null;
    do {
       synchronized(queue) {
          if(queue.isEmpty())
              queue.wait();
        item = queue.remove(0);
      // process item
      } while(!Thread.currentThread.isInterrupted());
    // producer
    synchronized(queue) {
        if(queue.isEmpty())
          queue.notify();
       queue.add(item);
       }The use of synchronized blocks or methods is essential. They guard against conflicts and race conditions between different sections that change the same data.

  • A bug in wait and notify? -- help

    Now I am engaged in a simulation project. The threads are all controlled by the controller program, that is, they are often blocked and unblocked by using wait and notify methods. However, when I was debugging my program, there were always some errors occurring and halting the simulation. And I found that the cause was that the threads sometimes might halt after having executed the wait or notify methods!!
    Example,
    in thread 1, it would be blocked by a wait method like:
    synchronized(lock){
    lock.wait();
    System.out.println("Thread 1 go on.");
    In thread 2, it would unblock thread 1 with the notify method:
    synchrnoized(lock){
    System.out.println("Thread 2 would notify the threads blocked on lock.");
    lock.notifyAll();
    System.out.println("Thread 2 go on.");
    The simulation program controls the time to execute the thread 2. However, in debugging the program I often encountered the problem that thread 2 did notify thread 1 and thread would go on executing, but thread 2 would not go further. That is, the output is like:
    Thread 2 would notify the threads blocked on lock.
    Thread 1 go on.
    But the String, "Thread 2 go on." would not be printed out.
    It was so strange, and I repeated for tens of times, it always occurred here and there.
    Is it a bug of java?

    There seems to be nothing wrong with this to me:
    You should use better debugging messages. I couldn't read it the way you had it.
    public class BugThread extends Thread
        Object lock;
        Notifier notifier;
        public static void main(String[] arg)
            for(int i = 0; i < 5; i ++)
                Object lock = "lock " + i;
                Notifier noti = new Notifier(lock);
                BugThread bug = new BugThread(lock, noti);
                bug.start();
                noti.start();
        public BugThread(Object lock, Notifier notifier)
            this.lock = lock;
            this.notifier = notifier;
        public void run()
            int i = 0;
            while( i++ < 100)
                synchronized(lock)
                    System.out.println("Bug thread: "
                        + lock + " would block at Object: "
                        + lock);
                    try
                        lock.wait();
                    catch(InterruptedException ex)
                        ex.printStackTrace();
                    System.out.println("Bug thread: "
                        + lock + " unblocked at Object: "
                        + lock);
            notifier.stop();
    class Notifier extends Thread
        Object lock;
        public Notifier(Object lock)
            this.lock = lock;
        public void run()
            int i = 0;
            while(true)
                synchronized(lock)
                    System.out.println("Notifier: " + lock
                        + " would notify Bugthread blocking at object: "
                        + lock.toString() + ". time no." + i);
                    lock.notifyAll();
                    System.out.println("Notifier: " + lock
                        + " notified bugthread. time no." + i);
                System.out.println("Notifier: " + lock
                    + " go on working. time no." + i);
                i ++;
    }

  • Wait() and notify() or Semaphores with single permits?

    Hi,
    What's the difference between using wait(), notify() and single permitted Semaphores? Does using the latter affect the performance in massively multi-threaded environments?

    I wrote a very simple program to simulate a Queue like structure, and a Producer with a Consumer which both are running in separate threads. I changed the Queue class to hold only one value (It's not a queue any more, but the name didn't change). Then I used a boolean value, wait() and notify() methods of the Object class to ensure that every put() by the producer is followed by a get() by the consumer. Here's the Queue class code:
    class Queue {
         private int num;
         private boolean valueSet = false;
         synchronized void put(int n) {
              while(valueSet) {
                   try {
                        wait();
                   } catch(InterruptedException err) {
                        System.out.println("put() interrupted.");
              num = n;
              valueSet = true;
              notify();
              System.out.println("Put: "+n);
         synchronized int get() {
              while(!valueSet) {
                   try {
                        wait();
                   } catch(InterruptedException err) {
                        System.out.println("get() interrupted.");
              valueSet = false;
              notify();
              System.out.println("Got: "+num);
              return num;
    }Producer and Consumer classes simply repeat calling put() and get() methods respectively for a number of times. I also implemented all this by using Semaphores with single permits:
    import java.util.concurrent.*;
    class Queue {
         private int num;
         private final static Semaphore semCon = new Semaphore(0);
         private final static Semaphore semPro = new Semaphore(1);
         void put(int n) {
              try {
                   semPro.acquire();
              } catch(InterruptedException err) {
                   System.out.println("put() interrupted.");
              num = n;
              semCon.release();
              System.out.println("Put: "+n);
         int get() {
              try {
                   semCon.acquire();
              } catch(InterruptedException err) {
                   System.out.println("get() interrupted.");
              semPro.release();
              System.out.println("Got: "+num);
              return num;
    }Which one is better? Better in every aspect, such as performance, being maintainable, etc. I don't know whether it's a good idea to use Semaphores in these cases.
    Thanks for your reply.

  • IllegalMonitorStateException? wait() and notify()

    Can someone tell me what's the deal with wait() and notify() methods? Like how to use them properly? Right now I have two threads, one being the main program and the other should run occationally when I need it... I try to get the second to wait() and second.notify() when I want to to run but IllegalMonitorStateException... so if you know a tutorial or you can explain it me it'll be great!
    Thanks!

    This is a bit hard to answer without a code example. Have you gone through the tutorial available on this topic?
    http://java.sun.com/docs/books/tutorial/essential/threads/index.html
    If you have already looked at these, post your sample code (inside code tags, please - use the code button above) so others can read it and run it.

  • Why  wait  and notify kept in object class only

    why wait and notify kept in object class only. is it maintain locks while doing wait and notify . please explain internals,

    What do you mean in Object class "only"? If they're in Object, then they're in ALL classes.
    They're in Object because any Object can serve as a lock.
    For details of how to use them, see a Java threading tutorial such as http://java.sun.com/docs/books/tutorial/essential/threads/

  • Object.wait(): IllegalMonitorStateException: current thread not owner

    How can I identify the owner? I searched the Thread*-Classes but didn't see any method which identifies the owner.

    Or, from the documentation for Object.wait():
         * The current thread must own this object's monitor.and
         * This method should only be called by a thread that is the owner
         * of this object's monitor. See the <code>notify</code> method for a
         * description of the ways in which a thread can become the owner of
         * a monitor. and
         * @exception  IllegalMonitorStateException  if the current thread is not
         *               the owner of the object's monitor.Seems like a lot of people are getting broken downloads nowadays that don't include the documentation :-(

  • Garbage collection of objects created inside a method

    I have method and inside the method I create new Objects I mean I instantiate objects using new and call some methods on these objects.
    once the method execution is completed and control goes to caller of the method will all the object created inside the method will be garbage collected ?
    here with code
               public List<StgAuditGeneral> getAudits(
              List<StgAuditGeneral>  audits= new ArrayList<StgAuditGeneral>();
                  for(Map<String, String> result :results ){
                   audits.add(new MapToObject<StgAuditGeneral>() {
                        @Override
                        public StgAuditGeneral getObject() {
                                             StgAuditGeneral  stg= new StgAuditGeneral();
                             return stg;
                   }.getObject());
              }in the above method I cam creating tons of objects wil they be garbage collected immediatedly after jvm leaves the method ?

    user11138293 wrote:
    I have method and inside the method I create new Objects I mean I instantiate objects using new and call some methods on these objects.
    once the method execution is completed and control goes to caller of the method will all the object created inside the method will be garbage collected ?If there are no reachable references, to those objects, then when the method ends, they become eligible for GC. If and when they are actually collected is something we can't know or control, and generally don't care about. The only guarantee is that everything that can be collected will be collected before an OutOfMemoryError is thrown. So from our perspective, once it's eligible for collection, it is effectively collected.
    If you pass references to those objects to something else that holds onto them after the method ends, then they are still reachable, and not eligible for collection.
    However, you almost never need to even think about whether something is eligible for GC or not. It works pretty intuitively.

  • Keep getting this prompt when I close a tab: ASSERT: Giving up waiting for the tab closing animation to finish (bug 608589) Stack Trace: 0:([object XULElement],[object XULElement],0) How do I get rid of it?

    ASSERT: Giving up waiting for the tab closing animation to finish (bug 608589)
    Stack Trace:
    0:([object XULElement],[object XULElement],0)
    Happening since I went to the 4.0b9 beta. Thanks for any help in getting rid of it.

    They're still working on fixing that Bug - https://bugzilla.mozilla.org/show_bug.cgi?id=608589 - a fix for another Bug - https://bugzilla.mozilla.org/show_bug.cgi?id=613888 - landed earlier this week which might have fixed it. Unless you are willing to install a nightly Trunk which has the latest fixes, you'll have to wait for 4.0b10 for the fix.

  • How to get caller object reference from a method

    Hi,
    I am working a already existing Java Swing project, now I got a problem, in a method I need to get the caller object reference otherwise, I can't succeed this operation. So please tell me a way how to get the caller object reference from a method. that method would be static or regular method anything will do for me.
    Edited by: navaneeth.j on Jan 29, 2010 11:20 PM

    navaneeth.j wrote:
    Actually my doubt is, I have a method "addition" method, which is using by many classes so my requirement is in the addition method I want to write a code snippet which will identify and get the the caller object. Actually I tried Reflection.getcallerclass but there I am getting "CLASS" object not the actual object reference, but I want object reference.
    Actually we have a huge project which is writen plain JAVA, so in this project the authors written the Database connection package for single database transaction. so now we are using this project source code for JSF application in this web application the DB package has serve based on the dynamic db connection parameters, so if we want to change this package fully means need to solve the dependency problem in hundreds of classes, so my point is if I can access the caller object in the DB package when ever it gets called by any class from any where of the project. So actually I liked Reflection.getcallerclass, the way of implementation perfectly works for me but it is not giving caller object reference, if something gives the caller object then I can get the DB connection parameters then there is no need to pass the parameters in the hierarchy.You can add a parameter (of type Object) to your addition() method
    and everywhere you call the addition() method also pass this (which from the POW of the addition() method will be a reference to the calling class instance).
    There may be alternative solutions
    but none that require less effort.

  • Object system and its method genericinstantiate?????????????

    Hi Experts,
    I have a workflow, in this workflow header tab there is no triggering event is mentioned .
    no business object no triggering event .
    when i checked the workflow the first task is created by business Object system and its method genericinstantiate.
    now i am not able to understand what is the role of BO system and this method.
    Also i am not able to understand how this workflow is getting triggered is this method is helping this workflow to get triggered.
    thanks in Advance
    Thanks & Regards
    Anit Gautam

    when i checked the workflow the first task is created by business
    Object system and its method genericinstantiate.
    now i am not able to understand what is the role of BO system and this method.
    If you are not able to trace from where this event is getting triggered, the simple way to find how the task is receving the event is
    1.Switch on the event trace by using the txn SWELS.
    2. Trigger the workflow by using the same event either from SWUE txn or directly stsrting the process which raises this event.
    3. Onc the event is triggered , go to SWEL txn and check what are the workflow templates and tasks are receiving the event which you have triggered.

  • Can't close tab. Don't get an X in tab.ASSERT: Giving up waiting for the tab closing animation to finish (bug 608589) Stack Trace: 0:([object XULElement],[object XULElement],0)

    error msg: ASSERT: Giving up waiting for the tab closing animation to finish (bug 608589)
    Stack Trace:
    0:([object XULElement],[object XULElement],0)

    A work around is goto about:config
    toggle the following line so that it is set to false.
    browser.tabs.animate

  • Under CentOS 6 x64, Java Thread.sleep()/Object.wait() will be influenced.

    Under CentOS 6 x64, Java Thread.sleep()/Object.wait() will be influenced while changing OS time.
    I found a BUG in java bug list. The bug id is 6311057 with fixed status. But I find it still existing.
    Under CentOS6 x64 platform, on JDK1.6.0_33, the bug still exists.
    But under CentOS5 x64 platform, on same JDK, the problem does not exist.
    Could anyone give me help? Thanks.
    The bug's link is http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6311057
    Edited by: user10222290 on 2012-6-13 下午9:22

    user10222290 wrote:
    One server could want to synchronize it's OS time with another server when they connected each other for some business reasons. I have 3 computers running pretty much continuously with time synchronised from one of the internet time servers. They never seem to be more than about 1/10 th second apart and any time corrections are very very small.
    Some threads have started to run before changing OS time, so these thread's sleep process will be influenced sometime seriously.I understand that but I would only expect this to be a problem when there is a significant change to the OS time. If each server is synchronized to a time server then the time corrections will be very very small.
    If OS time was turned back some days, these thread could not wake up untill some days passed.Agreed but why would the "OS time be turned back some days" ?
    This whole problem seems to me to arise because the servers are not time synchronized. Now I understand that there may be concerns about the security of external time servers but it is easy enough to make one of the local servers a master and act as a time server to the others.
    I have a small server that typically services some 30 or so external clients. I don't have any control over the clients and do not know anything about the setting of their system clocks. The clients send a time signal as part of a heartbeat and from this the server keeps track of the local time on each client and compensates for any difference when writing logs. I have seen this difference as big as 4 months but the compensation corrects it to within about a second. No adjustment of clocks is required for this.
    I still don't see this 'bug' as a serious bug. I just see a design problem to be solved without changing the OS time on any computer. I know this can be done since I do it. The only problem I see is if you want an accuracy of better than about 20 mS but that does not seem to be required for your system.
    Note - if Oracle accept your new bug report it could take years to fix even if lots of people vote for it to be fixed.

  • Pass an object from a static method

    Hi,
    I'm trying to pass a reference to an object from a static method, but I get an error when compiling.
    Say for example I have this:
    public class obj1 {
    public void myMethod (int i, Object ob, etc...) {
    ...and I want to call this method from a method that looks like this:
    public class obj2 {
    public static int anotherMethod(...) {
    obj1.myMethod(1,this,...);
    ...Can I pass a reference from obj2 to obj1 any other way?
    Thanks alot.

    how can I get a reference to obj2 then?Pay no attention to zdude's answer - it's nonsense.
    You're confused about basic Java concepts. obj2 is a class, not an object. References point to objects, not classes. There is no obj2 object in the code you show, so you cannot have a reference to an obj2 object.
    Maybe if you post some more code, we can get an idea of what you're trying to do. You might want to try the New to Java forum.

  • CRM Middleware Monitoring: Adapter Status Information. Waiting Objects

    Hello
    I am having a problem sending messages of type RSREQUST from CRM to BW
    I have been seeing in the SMWP transaction that we have waiting objects in Request Status of Adapter Status Information.
    I dont know how I can start it or solve this error
    Thanks in advanced
    Best regards

    Hi,
    It seems that the maximum number of parallel processing threads(usually 5) have been set in ur system which is why the objects are in status WAIT. Status WAIT is not an error. To correct, would you check the transaction R3Ar3 for all requests tht are in running status. If you have 5 requests here, abort one or two out of them. Then go to SMQ2 and select the queue tht is in status WAIT. Unlock the queue immediately. It should change to status "READY" and should flow across to BW.
    Reward points if it helps !!
    Rgds
    Priyanka Bansal

Maybe you are looking for

  • Using text in JSpinner SpinnerNumberModel.

    I was wondering if there is a way that I can use text in JSpinner SpinnerNumberModel. I have created a spinner as following: JSpinner spinner = new JSpinner(new SpinnerNumberModel(0,0,127,1)); What I would like to do is put Text within the NumberMode

  • How i can synch my windows pc safari with my iphone safari?

    In the past I sync my windows pc safari with my phone  safari ( I am not sure how) and now I can see the bookmarks on my phone. I am looking to update my phone safari as i had add more bookmarks. How i can do that? i got iphone5s ios 8.1.1

  • Multiple Artwork Covers Issue & Grouping Question

    My favorite band is The Smashing Pumpkins. Their latest album +Teargarden by Kaleidyscope+ is being released one song at a time online for free and in 11 different limited EPs that will compose the whole album. My problem here is that there a two art

  • Upgrading to leopard from tiger help

    Im using a Macbook pro core duo with tiger OS, am I able to upgrade to Leopard OS with my Macbook Core2Duo install disks? or what can I do? I need to upgrade as soon as possible, but I dont have money actually till next month to buy a new install dvd

  • How to show simple chinese in jsp

    when I use simple chinese in jsp,in the portlet all the char convert into B>B-C&#147;B*B;C.B6B/,but in the servlet,all the simple chinese char it right,I have set the conentType = "text/html;gb2312",but the problem is still. somebody can help me! tha