Threads and notify

I have the following code fragment:
          synchronized (obj) {notify();}
Yet I get the following exception:
java.lang.IllegalMonitorStateException: current thread not owner
     at java.lang.Object.notify(Native Method)
How is that possible? Since I am in a sychronized block, I must own obj. How can I not be the owner for the purpose of notify()?
Thanks.
-- Russ Abbott

If you use sychronized (obj), you'll be obtaining a lock on the given object. That way, obj.notify() will work just fine.
By calling notify(), you're effectively calling this.notify()
Either synchronize on 'this' with a synchronized method, or call obj.notify().

Similar Messages

  • Posting topic to more than one thread and in different categories...

    Is there anything in the TOU we can "refer" to when users post the same topic in more than one thread and to add to that, more then one category? Case in point: http://discussions.apple.com/thread.jspa?messageID=8806009#8806009 (This is just one example)
    Limnos had a valid point. If we had a section in the TOU we could copy/paste from, I think it would help if we could refer to authority, ie., TOU.
    Thanks!
    Carolyn

    I wouldn't get into too much of a flury about that with end users. Notify as needed and let the moderators decide if it needs to be deleted. A good rule of thumb is you want the discussions to have:
    Everyone should feel comfortable reading Submissions and participating in discussions.
    That's from Terms of Use.
    And then there is:
    You agree to not interfere with or disrupt the Site.
    I'm seeing that logically one can conclude directing users not to crosspost may be considering interference with the site. I may suggest someone post in another forum if a solution is not transparent in the forum they are using, but that's as far as I'm comfortable bending the rules.
    I'm trying hard to keep my thumbs away from the keyboard when I see duplicate posts.

  • 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 in servlets?

    i am having a servlet , which is implementing wait and notify of java.lang.Object.
    when serving it for single request , its waiting and working fine...
    but for multiple requests its not serving properly. works one by one means the second request is waiting for finishing the first request just like SingleThreadModel (after finishing the first request only second request entering inside servlet)
    please help me to solve this?
    or is there any other way to call wait method without synchronized block??

    Shynihan wrote:
    or is there any other way to call wait method without synchronized block??No, and that's partly because if wait or notify is the only thing in the synchronized block then you probably aren't using them right. The problem is blocking the server thread. Servlet engines use a thread pool to execute transactions, when a new transaction comes in a thread is taken from the pool to run it, and there's usually a limited number of threads in the pool. If there's no threads left then the transaction will wait for another to finish.
    If your servlets freeze up, then that's a thread gone from the pool.
    And remeber the unlocking transaction may never arive. The client could go down at any time, leaving the server thread permanently hung.
    You need to move this waiting to the client side. If the transaction cannot proceed then return a "come back later" response immediately. The client can then retry after a decent interval.

  • 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.

  • 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/

  • SwingEvent thread and synchronization

    I am having a problem where my app keeps locking up. I have a swing application that receives asynchronous realtime messages from a server.
    On receiving these messages my views are required to update the components. I do this my calling a method with a synchronized block that updates the views components in a SwingUtilities.invokeLater clause.
    This seems to work fine. However, sometimes when I click a menu item/button the app locks up.
    I have put some debug in that shows me the synchronized block started but did not complete?!?!
    I think this tells me that the SwingEvent thread interrupted my external notification thread, and caused some sort of deadlock.
    If this is the case then why does my synchronized block of code not complete. I am not altogether sure what I should synchronize around.
    For example I am doing something like this>
    public void notify(Model model){
    if(model == null) return;
    synchronized(model){
    System.out.println("started");
    SwingUtilities.invokeLater(new Runnable(){
    componentA.setText(model.getName());
    System.out.println("ended");
    My output when it locks is like this
    started
    ended
    started
    ended
    started
    At this point the app is frozen.
    So I guess what I am asking is as follows>
    Is the SwingEvent thread interrupting my external notification thread?
    If so, why is the synchronized block not completing.
    What should I synchronize?
    Any help would be greatly appreciated.
    Dr Nes

    If there is a deadlock (which seems likley), and you are running on jdk 1.4.x, you simply have to do Ctrl-Break (on windows) or crtl-\ (on unix) to get the complete state of all threads and and lock objects. From this it should be fairly simple to figure out what is causing the problem.

  • Difference between Thread and Process

    Hi!
    I was googling about this subject, and I found this old thread on google: http://forum.java.sun.com/thread.jspa?threadID=580508&messageID=2939031
    My specific doubt is: can one thread inside in a process affect other thread inside in other process?
    But, actually, the terms thread and process are not clear for me yet. I don't know what is the exact difference yet.

    > If I start a JVM, and Microsoft Word, and a web
    browser, that's three processes. A process is an
    OS-level construct.
    Threads refer to concurrent execution paths withina
    given process. Just like multiple processes canrun
    in parallel within the OS, so can multiple threads
    run in parallel within a process.
    That's exactly what I understood. So, I suppose that
    a thread in a process cannot affect other thread in
    other process, can it?Not at the Java language level.
    I mean, the wait( ), notify(
    ), etc, methods do not make sense if you consider
    threads of different process, right?Right. Those are just methods that you call on objects. The same rules apply to them as to other methods. Now, with RMI, it might be possible to call wait(), etc. on a remote object. I've never use RMI, but I don't think that actually works. If it does, I expect it would be in an RMI tutorial.
    Indeed, very confusing. They could facilitate,
    defining a clear distinction between thread and
    process.Well, there is a distinction in their "interface," if you will. It's just that their implementations can overlap.
    Kind of like how a List and a Set are different, but you could implement a Set by composing it with a List.

  • 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.

  • Wait and notify

    I have a main that calls a drawing window. The user draws in the window and clicks a button when finished drawing. Then main then gets this image. I don't know how to call the getImage in the main ONLY after the user has clicked the button in the draw window, however. I've heard about wait and notify commands, but I don't know how to use them. Can anyone help me? Thanks.

    Oh my... I'm not a java superstar. I'll post my code and maybe someone can help me. I tried running wait, but it says not thread owner or something weird.
    Main:
    public static void main (String [] args) throws IOException, InterruptedException, AWTException
            Image image = null;
            PaintArea pa = new PaintArea ();
            pa.loadArea (pa);
            //After screen capture
            image = pa.getImage ();}PaintArea:
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    class PaintArea extends Frame
        static int x, y;
        static Image image;
        Canvas canvas = null;
        PaintArea ()
            setSize (110, 160);
            setVisible (true);
            addWindowListener (new WindowAdapter ()
                public void windowClosing (WindowEvent e)
                    hide ();
        public void loadArea (PaintArea pa) throws InterruptedException
            Button button = new Button ("Save");
            Canvas drawArea = new Canvas ();
            drawArea.setSize (100, 100);
            canvas = drawArea;
            pa.setLayout (new BorderLayout ());
            pa.add (drawArea, BorderLayout.CENTER);
            pa.add (button, BorderLayout.SOUTH);
            pa.show ();
            Graphics g = drawArea.getGraphics ();
            final Graphics g2 = g;
            final PaintArea pa2 = pa;
            button.addActionListener (new ActionListener ()
                public void actionPerformed (ActionEvent ae)
                    try
                                          image = saveScreen (pa2);
                    catch (AWTException e)
                        System.err.println (e);
                        System.exit (1);
                    catch (InterruptedException ie)
                        System.err.println (ie);
                        System.exit (1);
            drawArea.addMouseListener (new MouseAdapter ()
                public void mousePressed (MouseEvent me)
                    x = me.getX ();
                    y = me.getY ();
                    g2.fillOval (x - 5, y - 5, 10, 10);
            drawArea.addMouseMotionListener (new MouseMotionAdapter ()
                public void mouseDragged (MouseEvent me)
                    x = me.getX ();
                    y = me.getY ();
                    g2.fillOval (x - 5, y - 5, 10, 10);
        public Image saveScreen (PaintArea pa) throws AWTException
            Image image = null;
            try
                image = createImage (new Robot ().createScreenCapture (pa.getDrawArea ().getBounds ()).getSource ());
            catch (NullPointerException npe)
                System.err.println (npe);
                System.exit (1);
            return image;
        public Picture getImage ()
            return image;
        public Canvas getDrawArea ()
            return canvas;
    }Could someone please run that and try to make the pa.getImage() in the main happen only after the button in Paint Area is pressed? Thanks!

  • Help/advice needed SwinEvent thread and synchronization

    I am having a problem where my app keeps locking up. I have a swing application that receives asynchronous realtime messages from a server.
    On receiving these messages my views are required to update the components. I do this my calling a method with a synchronized block that updates the views components in a SwingUtilities.invokeLater clause.
    This seems to work fine. However, sometimes when I click a menu item/button the app locks up.
    I have put some debug in that shows me the synchronized block started but did not complete?!?!
    I think this tells me that the SwingEvent thread interrupted my external notification thread, and caused some sort of deadlock.
    If this is the case then why does my synchronized block of code not complete. I am not altogether sure what I should synchronize around.
    For example I am doing something like this>
    public void notify(Model model){
    if(model == null) return;
    synchronized(model){
    System.out.println("started");
    SwingUtilities.invokeLater(new Runnable(){
    componentA.setText(model.getName());
    System.out.println("ended");
    My output when it locks is like this
    started
    ended
    started
    ended
    started
    At this point the app is frozen.
    So I guess what I am asking is as follows>
    Is the SwingEvent thread interrupting my external notification thread?
    If so, why is the synchronized block not completing.
    What should I synchronize?
    Any help would be greatly appreciated.
    Dr Nes
    I can only assume that

    I am having a problem where my app keeps locking up. I have a swing application that receives asynchronous realtime messages from a server.
    On receiving these messages my views are required to update the components. I do this my calling a method with a synchronized block that updates the views components in a SwingUtilities.invokeLater clause.
    This seems to work fine. However, sometimes when I click a menu item/button the app locks up.
    I have put some debug in that shows me the synchronized block started but did not complete?!?!
    I think this tells me that the SwingEvent thread interrupted my external notification thread, and caused some sort of deadlock.
    If this is the case then why does my synchronized block of code not complete. I am not altogether sure what I should synchronize around.
    For example I am doing something like this>
    public void notify(Model model){
    if(model == null) return;
    synchronized(model){
    System.out.println("started");
    SwingUtilities.invokeLater(new Runnable(){
    componentA.setText(model.getName());
    System.out.println("ended");
    My output when it locks is like this
    started
    ended
    started
    ended
    started
    At this point the app is frozen.
    So I guess what I am asking is as follows>
    Is the SwingEvent thread interrupting my external notification thread?
    If so, why is the synchronized block not completing.
    What should I synchronize?
    Any help would be greatly appreciated.
    Dr Nes
    I can only assume that

  • About wait() and notify()

    Hello all,
    I have a small problem.Before explaining the problem as such,ill give u a breif description of what i am trying to do
    I have two layers.The upper layer is sender and the lower one is the reciever.Now ,there's only one reciever thread and a number of sending threads.So when one sender sends something...the reciever will start processing with the data.
    In the mean time ,if another sender thread wants to send something to the reciever thread, then it must wait until the reciever enters wait state after it's current processing.
    So the reciever should notify the sender thread which is in wait state...
    My probelm is the sender thread if enters in to wait state once...I'm not able to notify it again when the reciever thread is ready for it.
    Hope some one among u can help me out
    thanking u in advance
    regards
    anees

    you could make the method that does the processing in the receiver, synchronized. that way, the jvm will take care of your requirement.
    if you have to use the wait- notify scheme, then try using notifyAll() instead of notify()

  • Thread and Exception

    I'm developping a library in Java that deals with network.
    I've got a multithreaded class that use a socket.
    In the run() function i keep reading the socket, that implies i have to try, catch IOException.
    The matter is that as i'm developping a library, i'd like to let the user choose what to do with this exception. I'd like to throw the exception.
    But the prototype of the run function don't allow to throw anything.
    Can anyone can give me a trick to manage a fake throw ?
    thank you
    Fabrice

    >
    - Runtime exceptions may be uncaught, without any
    compiler warning.This is unrelated to multithreading. By definition,
    RuntimeException, Error, and their descendants are
    unchecked exceptions, meaning they're usually preventable
    with good coding practices and/or you can't recover from
    them anyway, so there's no reason to explicitly declare them.
    A completely separate issue is that any exceptions--checked or
    unchecked--thrown in thread that you spawn will not be visible to the
    spawning thread.
    - hashtable may not be read by the user.Not sure what you mean here. If there's some hashtable in the new thread
    that you want to read, you can do so. You just need to provide a reference
    to it before starting the thread.
    - listener, in event style method, may not be
    register.Again, not sure what you mean here, but you CAN register listeners so that the original thread
    is notified of events in the new thread.
    >
    What's the worse solution !!
    Anyone knows why it's impossible to declare run() as a
    throwing exception function ?Your run method can't throw an exception because the declaration of the method it's implementing doesn't allow it. The reason Run.runnable doesn't allow it is beacause it doesn't make any sense for an independent thread to throw an exception back to the thread that spawned it.

  • 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.

  • A problem with Threads and MMapi

    I am tring to execute a class based on Game canvas.
    The problem begin when I try to Play both a MIDI tone and to run an infinit Thread loop.
    The MIDI tone "Stammers".
    How to over come the problem?
    Thanks in advance
    Kobi
    See Code example below:
    import java.io.IOException;
    import java.io.InputStream;
    import javax.microedition.lcdui.Graphics;
    import javax.microedition.lcdui.Image;
    import javax.microedition.lcdui.game.GameCanvas;
    import javax.microedition.media.Manager;
    import javax.microedition.media.MediaException;
    import javax.microedition.media.Player;
    public class MainScreenCanvas extends GameCanvas implements Runnable {
         private MainMIDlet parent;
         private boolean mTrucking = false;
         Image imgBackgound = null;
         int imgBackgoundX = 0, imgBackgoundY = 0;
         Player player;
         public MainScreenCanvas(MainMIDlet parent)
              super(true);
              this.parent = parent;
              try
                   imgBackgound = Image.createImage("/images/area03_bkg0.png");
                   imgBackgoundX = this.getWidth() - imgBackgound.getWidth();
                   imgBackgoundY = this.getHeight() - imgBackgound.getHeight();
              catch(Exception e)
                   System.out.println(e.getMessage());
          * starts thread
         public void start()
              mTrucking = true;
              Thread t = new Thread(this);
              t.start();
          * stops thread
         public void stop()
              mTrucking = false;
         public void play()
              try
                   InputStream is = getClass().getResourceAsStream("/sounds/scale.mid");
                   player = Manager.createPlayer(is, "audio/midi");
                   player.setLoopCount(-1);
                   player.prefetch();
                   player.start();
              catch(Exception e)
                   System.out.println(e.getMessage());
         public void run()
              Graphics g = getGraphics();
              play();
              while (true)
                   tick();
                   input();
                   render(g);
          * responsible for object movements
         private void tick()
          * response to key input
         private void input()
              int keyStates = getKeyStates();
              if ((keyStates & LEFT_PRESSED) != 0)
                   imgBackgoundX++;
                   if (imgBackgoundX > 0)
                        imgBackgoundX = 0;
              if ((keyStates & RIGHT_PRESSED) != 0)
                   imgBackgoundX--;
                   if (imgBackgoundX < this.getWidth() - imgBackgound.getWidth())
                        imgBackgoundX = this.getWidth() - imgBackgound.getWidth();
          * Responsible for the drawing
          * @param g
         private void render(Graphics g)
              g.drawImage(imgBackgound, imgBackgoundX, imgBackgoundY, Graphics.TOP | Graphics.LEFT);
              this.flushGraphics();
    }

    You can also try to provide a greater Priority to your player thread so that it gains the CPU time when ever it needs it and don't harm the playback.
    However a loop in a Thread and that to an infinite loop is one kind of very bad programming, 'cuz the loop eats up most of your CPU time which in turn adds up more delays of the execution of other tasks (just as in your case it is the playback). By witting codes bit efficiently and planning out the architectural execution flow of the app before start writing the code helps solve these kind of issues.
    You can go through [this simple tutorial|http://oreilly.com/catalog/expjava/excerpt/index.html] about Basics of Java and Threads to know more about threads.
    Regds,
    SD
    N.B. And yes there are more articles and tutorials available but much of them targets the Java SE / EE, but if you want to read them here is [another great one straight from SUN|http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html] .
    Edited by: find_suvro@SDN on 7 Nov, 2008 12:00 PM

Maybe you are looking for

  • Substitution not working

    Hi Friends, I created a substitution rule as follows (Call point 2 - Line item level): prerequisite: BSEG - KOSTL = 'ABC' AND BSEG - MWSKZ = 'V1' Substitutions (if prerequisite is met) BSEG - MWSKZ = 'V2' Logically, this seems to be correct. But when

  • How to define RFC parameters

    Hi Experts, i am using a RFC FM to from SRM system to ERP system. in ERP system the RFC FM parameters refer to some structures or tables which are not in SRM system. but i should transfer these parameters in SRM system to call this RFC. can anyone te

  • How to identify and update the DB parameters (no SYS access)

    Hi experts, I have to check some parameter values for an OID tuning I do not have sys access, I have only schema user access Now how do I see the values of SGA_TARGET, db_cache_size etc parameter I manage to see these var in init.ora file under /dbs

  • Solaris 8 config for DSL

    I want to reconfigure my standalone SunBlade100 for DSL service. The OS is Solaris 8 10/01, and is currently configured for dial-up access to an ISP. I've edited the etc/hosts, etc/resolve.conf, and etc/nsswitch.conf files, and I created an etc/defau

  • AR BW Project

    Hi All, I am working on AR BW Project. I want to get ZGRUP field to BW. Its in KNB1 table customers (company code). 0FI_AR_4 is the extractor and the tables are BSID and BSAD for that extractor. ZGRUP is the group key and I want to get the informatio