Stuck with wait() and notify()

Hi,
I have a problem understanding synchronous access.
I have an object that should provide a list of data. The list is used later in my code, but it would increase performance to load it in a separate thread at the beginning. However it is possible that the list is not ready when the first other object tries to access the list.
I thought that this code should solve the problem
public class SingleObject implements Runnable {
     ArrayList list;
     public SingleObject(){
          list = new ArrayList();
     public synchronized void run() {
          try {
               makeALongProc(100);
          } catch (InterruptedException e) {
               e.printStackTrace();
          notify();
     private synchronized void makeALongProc(int size) throws InterruptedException{
               System.out.println("...doing something ...");
               Thread.sleep(5000);
               for (int i = 0 ; i < size ; i++ ){
                    list.add(""+i);
               System.out.println("finished!");
               notifyAll();
     public synchronized String getValueAt(int pos) throws InterruptedException{
          wait();
          return list.get(pos).toString();
     public synchronized List getList() throws InterruptedException{
          wait();
          return list;
} The object is invoked by the following code.
public class ThreadProject {
      * @param args
     public static void main(String[] args) {
          System.out.println("...starting thread...");
          SingleObject so = new SingleObject();
          Thread th = new Thread(so);
          th.start();
          try {
               System.out.println("waiting ...");
               List list = so.getList();
               System.out.println("got list"+list.size());
               String sso = so.getValueAt(5);
               System.out.println(sso);
          } catch (InterruptedException e) {
               e.printStackTrace();
}Unfortunateley this is not doing what I have expected. Instead of calling the methodsso.getList() and so.getValueAt() it enters so.getList() and waits and waits....
Can anybody give my a clue or an explanation what I am doing wrong?
Regards
Sas
Message was edited by:
Poncho1975

I have tried a little bit further.
I changed the following part:
public class SingleObject {
     ArrayList list;
     public SingleObject(){
          list = new ArrayList();
     public synchronized void makeALongProc(int size) throws InterruptedException{
          System.out.println("...doing something ...");
          Thread.sleep(5000);
          for (int i = 0 ; i < size ; i++ ){
               list.add(""+i);
          System.out.println("finished!");
          notify();
     public synchronized String getValueAt(int pos) throws InterruptedException{
                if (list==null || list.size()<=pos){
                      wait();
          return list.get(pos).toString();
     public synchronized List getList() throws InterruptedException{
          if (list==null){
                      wait();
          return list;
}and ...
public class ThreadProject {
      * @param args
     public static void main(String[] args) {
          System.out.println("...starting thread...");
          final SingleObject so = new SingleObject();
          Thread th = new Thread(new Runnable(){
               public synchronized void run() {
                    try {
                         so.makeALongProc(100);
                    } catch (InterruptedException e) {
                         e.printStackTrace();
          th.start();
          try {
               System.out.println("waiting ...");
               List list = so.getList();
               System.out.println("got list"+list.size());
               String sso = so.getValueAt(5);
               System.out.println(sso);
          } catch (InterruptedException e) {
               e.printStackTrace();
}Now I am satisfied. Every call on a method from this object would lead to the situation, that either makeALongProc is called first or all other methods must wait until makeALongProc has been called once to fill the array.
However I suppose that accessing elements of a list with a synchronized object is not a good decision. I would rather take only the whole List and do all other access outside of the object.
Regards
Poncho

Similar Messages

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

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

  • 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 ++;
    }

  • Stuck with waiting for changes to be applied to syncing?

    Am stuck with waiting for changes to be applied to syncing?
    what can I do?

    Did yo try all of these:
    SOLUTION: Some Music Won't Play After Upgrading Your iPhone To iOS7
    Red square in red circle cannot play songs
    My iPod isn't playing certain songs. Help?
    Remove Red Circles with Square in middle

  • I was fooling around with the "reader" feature on my New iPad. I am now stuck with that and can't get out. Even my four digit code is read out in a machine voice and the iPad wont boot. How do I get out of this. Tried the red arrow slider. shut of the iPa

    I was fooling around with the "reader" feature on my New iPad. I am now stuck with that and can't get out. Even my four digit code is read out in a machine voice and the iPad wont boot. How do I get out of this. Tried the red arrow slider. shut of the iPa

    James,
    I cannot get into Settings! It keeps reading out Slide to Unlock when I try to slide teh arrow to open the fpur digit entry boxes.

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

  • HT2731 there is no option in my ipod for credit card as none. so what shoud i do am stuck with it.and i dont have any credit card so from where am i going to fill that option?

    there is no option in my ipod for credit card as none. so what shoud i do am stuck with it.and i dont have any credit card so from where am i going to fill that option?

    There are instructions on this page for how to create an account without giving a credit card number (i.e. select a free app and create an account) : http://support.apple.com/kb/HT2534

  • Duplicating files on Top "Level" of HD in Yosemite stuck with PENDING and "X"

    Duplicating files on Top "Level" of HD in Yosemite stuck with PENDING and "X"-- which is incredible as it is happening on both my 2010 MBP-13" and my daughter's brand new MacBook Space gray:
    Go to the highest level on your hard drive --- where the SYSTEM and APPLICATIONS and USERS folders are located.  Now take any file or folder that is there (small or big) and click on it, the either choose "duplicate" or do cmd-d to make a duplicate of that file.  WHAT HAPPENS?
    For me-- the file duplicates but the icon has a progress bar image  along the

    I HOPE THIS HELPS people to see what I'm getting on the top level only:  Here are 2 images -- a before and after:  I have a very plain empty folder called "Test Folder 1 May 2015" in the first one (along with some other folders) and then in the second one you can see I duplicated that folder -- but it now has a progress bar and and "x" showing!  (Just the "duplicated" file - the one with copy in the name).  This is a screen shot (using "Totalfinder" if anyone is wondering).  Same with my daughter's new MacBook (and she has essentially nothing on it, is not using TotalFinder - but the same problem.  Hey, maybe it's not a problem, maybe it's a "feature" of Yosemite or just the way it treats root level folders now--- but I sure would like to get rid of this weirdness if possible without breaking the system!

  • TS1702 I just had to restore my iPhone.  After everything has been backed up from the iCloud, 4 of my apps (Facebook, Twitter, Pinterest and Instagram) will not comeback.  They are stuck on "Waiting" and I cannot open or delete them.  HELP, please!!!

    I just had to restore my iPhone.  After everything has been backed up from the iCloud, 4 of my apps (Facebook, Twitter, Pinterest and Instagram) will not comeback.  They are stuck on "Waiting" and I cannot open or delete them.  HELP, please!!!

    I just had to restore my iPhone.  After everything has been backed up from the iCloud, 4 of my apps (Facebook, Twitter, Pinterest and Instagram) will not comeback.  They are stuck on "Waiting" and I cannot open or delete them.  HELP, please!!!

  • AI have an iPad and iPhone but am stuck with Tiger and Leopard. Will I stir be able to get my email on my PowerBook if I after I upgrade to iCloud?  I don't have the cash to upgrade the mac right now.

    I have an iPad and iPhone but am stuck with Tiger and Leopard on my old powerbook G4.  Will I still be able to get my email on my PowerBook after I upgrade to iCloud?  I don't have the cash to upgrade the mac right now.  Just wondering what my email options are.  Thank You.

    You will be able to get your mail on the PowerBook. The calendars (iCal) will not sync; any events added to iPad and/or iPhone will not sync with the Mac but will sync with each other (that is: the mobile devices which are on iCloud). My  MacBook Pro (Lion) and iPad2 (iOS5) sync fine; I still get my Mail on iBook G4, MacBook Pro (Snow Leopard) and iMac (Snow Leopard). 
    Message was edited by: kennethfromtoronto

  • When downloading a app it get stucks in "waiting" and it never downloads?

    I try to download and app or update a app and it gets stuck in "waiting" and never downloads. Any answers will work so i can get the apps to download.
    Thank you

    Its not in pause. i double check and the security software setting, is there anyway I can access it from my phone?
    my apps setting are
    Automatic Downloads
    Music ON
    Apps  ON
    Use cellular Data  ON

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

Maybe you are looking for