Thread question wait() notify()

The wait method must be called inside a try block because it declares that it throws an InterruptedException. Under what condition will it actually throw that exception and print "Caught InterruptedException" in the code below?
public synchronized void amethod()
try{
wait();
}catch(InterruptedException ie)
System.out.println("Caught InterruptedException");
I tried similar code and when the thread was notified and continued no exception was thrown.
Thanks,
Darrin

The InterruptedException will be thrown if some other thread calls the interrupt method on the thread that is waiting.

Similar Messages

  • Wait/notify, await/signal, faster blockingqueue that scales with N threads

    Hi,
    I have been benchmarking a blockingqueue. It holds 100 items before writers block. It uses not-empty/not-full semaphores. Typical stuff.
    I have noticed that with 1 writer and 1 reader threads, using synchronized()+wait/notify is faster than reentrantlock+await/signal.
    I tried to find the point (in number of W/R threads) where reentrant lock is better.
    For the remainder os the discussion, I must say that I never use 'fair' rentrantlocks: I tested them and they are always slower than synchronized.
    So, I always use 'unfair' locks.
    The thing is, the tests results are messed up. I mean I would expect a monotonous progression in reentrant lock performance as the number of W/R threads is increasing. But the reality (on a dual core dual opteron) shows strange progressions. Without diving into numbers...
    I would like to hear about the experiences of other people relatively to:
    -queue implementations and readers semaphore, writers semaphores most efficient patterns.
    -scalability observations and implementation choices related to the number of threads to be concurrent.
    Of course I have been experimenting with notify()/signal() instead of notifyAll()/signalAll() in order to avoid waking up too many writers/readers that do not stand a chance to perform their enqueue/dequeue without going back to wait()/await() again (in my case, fairness isn't an issue for readers, and for the moment, I accept unfair enqueue from writers). Also, a reader can notify/signal not only a waiting writer but another waiting reader if the queue isn't empty after its own dequeue. I'm about to do the dual notify/signal for writers: not only notify/signal a waiting reader but also another waiting writer if the queue isn't full after its own enqueue.
    Of course, this good-intentions implementation ends up notifying/signaling a lot. I'm searching for a new way of thinking, in case I have been blinded by too much obsession on my current implementation...! :-)
    Thanks.
    PS: for those of you that wonders why I don't use j.u.c array blocking queue, that's because I need:
    a) many queues enqueue to be able to notify/signal a single thread (1 thread waiting to read many queues). This implies an externally plugged-in readers (not-empty) semaphore.
    b) enqueueMany(array), dequeueMany(int max) ->array

    In Java 5 ReentrantLock provides much better performance under contention than built-in sync. Conversely built-in uncontended sync is always much faster. In Java 6 contended built-in sync has pulled back some ground on ReentrantLock. So with only two threads it is not surprising that built-in sync is faster.
    So the switch over point depends on the level of contention. This is a function of the number of threads (and CPU's) and what they do while holding the lock and between holding the lock.
    For evaluating read/write synchronization you need to have a read operation that is relatively long to dominate the cost the heavier read-lock. You also need sufficient parallelism to allow enough concurrent readers to make overall reader "throughput" significant.
    Benchmarks are seldom that useful/insightful unless realistic access patterns and workloads are used.

  • Thread sends notify() before waiting thread says wait()

    In the code below the ref book I'm using "Sun certified Programmer for Java 2" had the calculator thread starting before the Reader thread was even created and hence the calculator thread was finished it's task and sending a notify() before the Reader even had it's socks on and saying wait()
    ( And this cost me a lot of time tryin to figure this problem out as the code must have being written for a Z80 processor and not a 2.4GHz P4)
    To fix this I put the calculator starting after the reader thread, but .......
    I would have thought that java would have some protection against this happening, ie, like a notify flag which a thread can set if it has done it's job BEFORE the waiting thread even starts waiting, ie a preemptive mechanism to help speed things up ?
    package MyPackage;
    public class Reader extends Thread {
    Calculator MyCalculator;
    public Reader(Calculator calc){
    MyCalculator = calc;
    public void run(){
    synchronized(MyCalculator){
    try{
    System.out.println("Waiting for calculation ... ");
    MyCalculator.wait();
    }catch (InterruptedException e){}
    System.out.println("Total is: " + MyCalculator.total);
    public static void main(String args []){
    Calculator calculator = new Calculator();
    //calculator.start();
    new Reader( calculator ).start();
    calculator.start();
    package MyPackage;
    public class Calculator extends Thread{
    int total;
    public void run(){
    synchronized(this) {
    for(int i=0; i<100; i++){
    total += i;
    System.out.println("Calculation complete, notifying waiting thread..");
    notify();

    It's up to the 'umble programmer to code it right. The code you quoted was crap.
    The most common way to wait is on a condition:
    while (hotAndBotherd())
        obj.wait();And then the notifying thread will take steps to change that:
    //code that cools off the hot and bothered
    obj.notify[all]();If the initial state of things is hot and bothered then there is no race condition: the first thread will wait.

  • Sleep or wait() / notify()  Which is better IYO

    Consider an app where a central object, like an information server is handed a query and an amount of time will pass before that information is available. For caching, many objects may ask the same question and be waiting on the same answer. Is it better to have the queries do a sleep loop to wait for the response or is it better for the queries to register with the server and call a wait(), then have the server issue a notify to objects that were waiting?
    Thanks for the advice.

    Thank you. I like sleep as well. Although with three little ones that can be a difficulty.
    I am having a difficulty with how to implement the wait notify. Can you tell me if the following is a good / bad / normal / horribly wrong example?
    // sorta code...
    // This class goes to a central location
    // or the network for an answer.  It represents one answer for one query.
    class InfoServerQuery extends Thread{
      volatile boolean isComplete = false;
      volatile String response = null;
      Vector pool = new Vector();
      public synchronized boolean isReady(Object obj){
        if(!isComplete){
          // Add object to answer pool
          pool.add(obj);
          return false;
        }else{
          return true;
      public void run(){
        try{
          // Get the information.......
          response = getInfo();
          // set isComplete
          isComplete = true;
          // notify all that are waiting.
          for(int a = 0; a < pool.size(); a++)
          synchronized(pool.get(a)){pool.get(a).notify();};
        }catch(Exception e){
          throw new RuntimeException();
    // This class asks the questions.
    class QueryClient{
      // instantiated in constructor
      InfoServerQuery q;
      public String getAnswer() throws Exception{
        while(!q.isReady(this)) synchronized(this){wait();};
        return q.response;
    }Thanks for any insights.

  • Behaviour of wait()/notify()

    Until recently, I was sure that notify wakes up only waiting threads. This is proven by this program:
    class X extends Thread {     // Incomplete
        final Object lock;
        X(final Object lock) { this.lock = lock;  }
        static void log(String msg){ System.out.println((System.currentTimeMillis() - start) + ", " + Thread.currentThread().getName() + ": " + msg);}
        static void sleep1(long time) {     try {Thread.sleep(time);} catch(InterruptedException ie) {log("sleeping interrupt");}}
        public void run() {
            try {
                log("waiting");
                synchronized(lock) {
                    lock.wait(); // halts forever
                log("waked up");
            catch(InterruptedException ie) {
                log("interrupted");
        static final    long start = System.currentTimeMillis();
        public static void main(String[] args) {
            Object lock = new Object();
            synchronized(lock) {lock.notify();} // notify
            new X(lock).start();  // create a thread to wait for the notification
    }However, the following code breaks the rule:
    class GamePlayer implements Runnable {     // Incomplete
        protected GamePlayer other;
        protected boolean myturn = false;
        protected synchronized void setOther(GamePlayer p) {
            other = p;
        synchronized void giveTurn() { // called by other player
            myturn = true;
            notify();          // unblock thread
        void releaseTurn() {
            GamePlayer p;
            synchronized(this) {
                myturn = false;
                p = other;
            p.giveTurn(); // open call
        synchronized void awaitTurn() throws InterruptedException {
            while (!myturn) wait();
        void move() { /*X.log("moving");*/ }
        public void run() {
            try {
                for (;;) {
                    if (Thread.currentThread().getName().compareTo("two") == 0) {
                        X.log("sleeping");
                        X.sleep1(500);
                    X.log("wainting");
                    awaitTurn();
                    move();
                    X.log("releasing");
                    releaseTurn();
             catch (InterruptedException ie) {} // die
        public static void main(String[] args) {
            GamePlayer one = new GamePlayer();
            GamePlayer two = new GamePlayer();
            one.setOther(two);
            two.setOther(one);
            one.giveTurn();
            new Thread(one, "one").start();
            new Thread(two, "two").start();
    }The thread "one" initially owns the monitor, it makes a move and releases the monitor notifying the thread "two". However, the second thread is still sleeping. When it awakes from the sleep, the notification is already sent but the second thread receives it! That is, thread should not be waiting for the monitor event in order to recieve the notification. I'm I missing something?

    Can anybody explain the need for synchronized blockin releaseTurn()?
    Variable "myturn" is modified by the other thread.Yes, it is modified by another thread. But there is only one active thread. SingleWriterMultiReader paradigm does not block access to a shared resource, it just guards the access by permition granting. I do see any race conditions in releaseTurn() that would need for the synchro block on "myturn", "other" fields.
    You need to synchronize both reading and writing of a
    shared variable to ensure that one thread sees the
    change made by another. This is the other fuction of
    keyword "synchronized" (besides exclusive execution
    of a block).However, notification is not sent in releaseTurn, it is done in giveTurn.
    One more question, there is only one possible
    situation to get notification (after myturn => true).
    Will the program work properly without the cycle in
    awaitTurn(): if (!myturn) wait();If you remove this statement, on the first iteration
    both threads will go into wait() and there will be
    no-one to notify them.The first thread will not wait, because it's "myturn" is true on the first iteration. It then gives turn to second. If secons have checked "myturn" before it will be waiting and the first thread will notify it. Alteratively, secon thread will check after the first thread had set it to true and will not wait again.

  • Simulating the wait/notify concept that Java has.

    Hi all,
    I need to simulate the wait/notify concept that Java has.
    My question is how do I get a Stored Procedure to wait (for a certain time period, once it times out the Stored Procedure can carry on but in an error state.) - (Like the "wait" in Java)
    And then another Stored Procedure to break this waiting state. (Like the "notify" Java).
    When the second stored procedure breaks the waiting state, the first stored procedure can carry on with it thread of execution.
    I have tried to use DBMS_Locks, but uncovered a few hiccups.
    Is there anything else I can try? ...
    Regards,
    Hilton

    Hi John,
    Thanks for the input, I have tried the using DBMS_Pipe and seems to have solved by problem.
    Will look into the DBMS_Alert as well.
    Thanks Again
    Hilton

  • Simple threads question (I think)

    I searched all over the forum, but wasn't able to find an answer for this question, so here it is:
    I simply wanna slow down execution of a loop. I'm been playing with threads to try and do this using wait(long) but I always get the current thread not owner exception...
    Same thing when I tried it with Runtime.wait(long) or System.wait(long). Can anyone offer any suggestions?

    I simply wanna slow down execution of a loop. To do this, use Thread.sleep:
    //start doing something
    try {
      Thread.sleep(100);
    catch (InterruptedException e) {}
    //carry on doing somethingThe above code will cause the currently executing thread to go to sleep for 100 milliseconds (It will actually sleep for an arbitrary time of at least 100ms, so you can't use it as a timer, but for slowing something down, it'll do the job fine).
    I'm
    been playing with threads to try and do this using
    wait(long) but I always get the current thread not
    owner exception...Using wait if you don't properly understand it is a very bad idea. It is used when you need an object to be in some consistent state before continuing execution: The current thread waits for some other thread to change the object's state and notify it that a change has been made, before waking up and re-checking the object's state (This isn't all done by the wait method alone, but this is the situation in which you would use it). If you don't know how to use it properly, you are likely to cause a deadlock or contention problem.
    You are getting the error because when you call an object's wait method, you must first own that object's lock (i.e. be inside a block of code that is synchronized on that object). When a thread calls wait, the object adds it to its pool of waiting threads, and when notify (or notifyAll) is called on the object, it wakes up one (or all) of the threads in its waiting thread pool. The newly wawoken thread(s) then go into the ready state and try to get the lock back before continuing execution.
    The long argument to wait is a (non-strict) maximum time that the thread should wait for before it wakes up anyway, whether or not notify has been called.
    Same thing when I tried it with Runtime.wait(long) or
    System.wait(long). Can anyone offer any >suggestions?Runtime.wait and System.wait should both not compile, giving an error that you are trying to call a non-static method from a static context (or something similar).

  • Have thread in wait, but calling notifyAll() does nothing

    I'm trying to learn how wait() and notify() work with Threads, and I've created the following classes to test them out. However, when I call notifyAll() to restart the other thread, my program just sits there. Doesn't exit or anything. Could someone please help me figure out what is happening?
    Here is my code:
    //my thread class, initializes variables and contains the methods to call wait, notify and run()
    public class MyRunClass extends Thread{
    public boolean A;
    int startNum;
         int endNum;
         public MyRunClass(int y, String name){
              super(name);
              startNum = y;
         public synchronized void passStartNum(){
              endNum = 10;
              if(startNum > 5){
                   startNum = 4;
                   endNum = 10;
                   try{
                        System.out.println(getName() +" going into wait " );
                        wait();
                   }catch(InterruptedException a){
                   System.out.println("falling out of wait");
              }else{
                   endNum = 5;
         public synchronized void myloop(){
              while(startNum < endNum){
                   System.out.println(getName() +" startNum: " + startNum +
    "end Num: " + endNum);
                   try{
                        Thread.sleep(100);
                   }catch(InterruptedException e){}
                   startNum++;
              if(getName().equals("Thread1")){
                   System.out.println("going to do notify");
                   notifyAll();
         public void run(){
              passStartNum();
              myloop();
    //my class with the main() and the creation of my two threads
    public class AThread{
         Thread myt;
         Thread myt2;
         public AThread(){
              myt = new Thread(new MyRunClass(1, "Thread1"));
              myt2 = new Thread(new MyRunClass(6, "Thread6")) ;
         public void startTh(){
              myt2.start();
              myt.start();
         public static void main(String args[]){
              AThread at = new AThread();
              at.startTh();
    //Any help would be really appreciated!! Thanks!

    The other responses are correct, but since this threads are a complicated topic, I'll add another rewording.
    You can only call wait or notify on an object when you have that Object's monitor/lock, that is when you are synchronized on that object. ie...
    Object lock = new Object();
    synchronized (lock) {
        lock.wait();
    }When a thread calls wait, it releases the lock, which enables another thread to grab the lock - possibly to call notify on the object, which would wake up a thread waiting on that object. (notifyAll wakes up every thread that is waiting on that object) Note that the newly-woken thread(s) still won't be able to run until the thread that called notify releases the lock, since they are still in a synchronized block.
    In terms of design, if you want a single thread to wait and be woken it is appropriate to call wait and notify on the thread in question. If you are running multiple threads, and are waiting to synchronize between the threads, it is often more appropriate to call wait and notify on an object shared amongst the threads.
    There are a barrage of articles and lessons on the net... try a search on thread monitors or synchronization.
    -Troy

  • Thread CPU time: does it include the time while thread is waiting

    Hi,
    My question is regarding the getCurrentThreadCpuTime() supported by the ThreadMXBean.
    I wonder if the returned time includes the time while the thread is waiting, i.e. after the thread calls wait() and before getting a notify() or a notifyAll().
    Thanks,
    Nuha

    CPU time is intended to reflect actual time executing on a CPU. If block for a lock/wait/sleep or other blocking operation like I/O then you don't consume CPU while blocked.
    On Solaris it is implemented using gethrvtime()
    If a VM used a busy-wait for something rather than blocking (not likely with wait()) then that's consuming CPU time.

  • RMI and Threads: Calling wait() on a remote object

    I created a counter as a remote object.
    Multiple clients are displaying the counter value.
    If one of the clients increments the counter, I want the displayed counter value on every client to be updated to the new value (of the counter on the server).
    Therefore every client starts a new thread to "listen" for changes of the countervalue. I wanted to call the wait() method on the remote object (the remote counter). But i think it will be called on the stub instead of on the actual remote object.
    Therefore i created a extra method waitForChange() on the remote object.
    public void waitForChange() throws RemoteException, InterruptedException {
         synchronized(this) {
              wait();
    This method only calls the wait() method. Now I'm sure it's called on the remote object and not on the stub.
    This works, but my question is: is there a better way to do this?
    Code:
    ==========================================
    The remote interface
    ==========================================
    import java.rmi.Remote;
    import java.rmi.RemoteException;
    public interface RemoteCounter extends Remote {
         void incrementCounter() throws RemoteException;
         int getCounterValue() throws RemoteException;
         void waitForChange() throws RemoteException, InterruptedException;
    } ==========================================
    The implementation of the remote interface
    ==========================================
    import java.rmi.*;
    import java.rmi.activation.*;
    import RemoteCounter;
    public class RemoteCounterImpl extends Activatable
         implements RemoteCounter {
         private static final long serialVersionUID = 1L;
         private int counter = 0;
         protected RemoteCounterImpl(ActivationID id, MarshalledObject data) throws RemoteException {
              super(id, 0);
         public void incrementCounter() throws RemoteException {
              synchronized(this) {
                   counter++;
                   notifyAll(); //Inform all clients of the new countervalue;
         public void waitForChange() throws RemoteException, InterruptedException {
              synchronized(this) {
                   wait();
         public int getCounterValue() throws RemoteException {
              return counter;
    }==========================================
    A piece of code registering the remote object
    ==========================================
    ActivationDesc desc = new ActivationDesc(agi, "RemoteCounterImpl", codebase, data);
    //Register with rmid
    RemoteCounter counter = (RemoteCounter)Activatable.register(desc);
    // Bind the stub to a name in the registry running on 1099
    Naming.bind("Counter", counter);==========================================
    The panel containing a button, a label
    which starts a new thread listening for
    counter value changes
    ==========================================
    import javax.swing.*;
    import java.awt.Dimension;
    import java.awt.event.*;
    import java.rmi.*;
    import org.personal.exam.services.RemoteCounter;
    public class PanelCounter extends JPanel {
         private static final long serialVersionUID = 1L;
         JLabel labelX = new JLabel("Press testbutton");
         Thread t;
         RemoteCounter remoteCounter;
         public PanelCounter()     {
              try {
                   jbInit();
              } catch(Exception e) {
                   e.printStackTrace();
         private void jbInit() throws Exception
              this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
              this.setPreferredSize(new Dimension(450,300));
              // The securityManager is required to make is possible
              // to download classes from the server
              if (System.getSecurityManager() == null) {
                   System.setSecurityManager(new RMISecurityManager());
              //Create a testButton to increment the counter          
              JButton testButton = new JButton("Increment");
              testButton.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent arg0) {
                        incrementCounter();
              this.add(testButton);
              //Add a label to display the counter value
              this.add(labelX);
              // Create thread to listen for counter value changes
              try {
                   remoteCounter = (RemoteCounter)Naming.lookup("Counter");
                   CounterValueChecker cvl = new CounterValueChecker(labelX, remoteCounter);
                   //Start a thread to listen for changes of the countervalue
                 t = new Thread(cvl);
                 t.start();
              } catch(Exception e) {
                   e.printStackTrace();
              this.setVisible(true);
         private void incrementCounter() {
              String message = "error";
              try {
                   remoteCounter.incrementCounter();
                   message = "Current value is " + remoteCounter.getCounterValue();
              } catch(Exception e) {
                   System.out.println("Test Exception: " + e.getMessage());
                   e.printStackTrace();
              labelX.setText(message);
    }==========================================
    The runnable implementation used by the
    thread to wait for counterchanges
    ==========================================
    import java.rmi.RemoteException;
    import javax.swing.JLabel;
    import org.apache.log4j.Logger;
    import RemoteCounter;
    public class CounterValueChecker implements Runnable {
         private JLabel counterLabel;
         private RemoteCounter remoteCounter;
         public boolean keepChecking= true;
         private Logger logger = Logger.getLogger(this.getClass());
         public CounterValueChecker(JLabel counterLabel, RemoteCounter remoteCounter){
              this.counterLabel = counterLabel;
              this.remoteCounter = remoteCounter;
         public void run() {
              while(keepChecking) {
                   int newVal = -1;
                   synchronized(remoteCounter) {
                        try {
                             //remoteCounter.wait();
    //this does not work. I think because the wait() method is called on the
    //stub instead of on the actual remote object
                             remoteCounter.waitForChange();
                        } catch (InterruptedException e) {
                             keepChecking = false;
                             break;
                        } catch (RemoteException re) {
                             re.printStackTrace();
                        try {
                             newVal = remoteCounter.getCounterValue();
                        } catch (RemoteException re) {
                             re.printStackTrace();
                        counterLabel.setText("New value: " + newVal);
    }This is just a little test. Actually I want to notify clients of changes in data displayed in a Table. If one client saves one record of the data, i want the new record to be displayed immediatly on all clients that are viewing the same data.

    I've been doing some reading about RMI and callback.
    As I understand it, there's a remote object is running on the client now as wel. And the server makes a call to the client.
    But now the server makes a call to one client.
    And the point is, I want all clients to be updated with the new value.
    Does this mean, I have to keep a list with references to all clients connected to the server?
    I my code the notifyAll() method causes all waiting Threads (running on several clients) to wake up and do something (getting the new counter value).

  • Need help : wait() & notify()

    Hi, I am working on a project which has multiple components. Components support basic commands like startComponent, stopComponent, suspendComponent & resumeComponent. I am using jmx mgmt interface to call start, stop, suspend & resume commands. I am also using timer task in my components. My component start purgeTimerTask during startComponent call.
    I want purgeTimerTask to wait when my component is suspended & purgeTimerTask should be notify() when my component get resumed.
    Following is the implementation of suspendComponent() method.
    public void suspendComponent()
            try
                if (null != purgeTimerTask)
                    synchronized (purgeTimerTask)
                           purgeTimerTask.wait();
            catch (InterruptedException e)
                logError("PurgeComponent.suspendComponent() - exception: " + e);
        }Calling suspendComponent() method from JMX mgmt interface, control is not coming out of suspendComponent() method.
    I am not able to understand what is the cause of not coming out of suspendComponent() method.
    I have implemented resumeComponent() method where i am calling purgeTimerTask.notify() to reactivate the timer task.
    Can any one guide me here how can i resolve this issue?
    Thanks & regards,
    Pawan Modi

    PawanModi wrote:
    Hi, Ok you are right. After debugging i found that my current (application) thread is waiting at following statement.
    purgerTimerTask.wait();And not coming out of this statement.
    It won't come out until some other thread calls purgerTimerTask.notify().
    But this isn't a safe way to use wait and notify. You should do something like this:
    [code[
    synchronized(someMonitor) {
    while(suspended) {
    someMontitor.wait();
    And resume like:
    synchronized(someMonitor) {
        suspended = false;
        someMonitor.notifyAll();
    }

  • Conceptual Thread question

    Good evening...
    i understand what multi-tasking and threading is.
    but what i'm having trouble with is the idea of having two threads communicate.
    for example a thread that reads several files simultaneously, and another thread that "requests" the most recent entry that was read from all the files.
    because it's not the entire object that runs in a separate thread right? it's really only the run() method, correct?
    thanks.
    so the run() method would have to do the work of reading the files and sorting what it reads, then stick it into a buffer where some other method of the object could return it when requested. is that the right way of thinking?

    Yes, something along those lines.
    Just because a Thread is running it doesn't prevent you from accessing its methods. Obviously attempting to call certain methods will throw IllegalStateExceptions and the like.
    If you want to get two Threads to communicate then you could either get one to regularly ask the other one questions, eg "do you have any more data for me?", or you could get one Thread to wait on the other Thread, thus only waking up when new data has arrived.
    In either case I would put some data buffer between them rather than actually within one of them.
    For example:
    public class ProducerThread extends Thread
      protected DataBuffer buffer;
      public ProducerThread(String filename, DataBuffer buffer)
        super("ProducerThread");
        this.buffer = buffer;
      public void run()
        try
          // Read in your data
          Iterator i = ...;
          while(i.hasNext())
            buffer.bufferData(i.next());
          buffer.setFinished(true);
        catch(Exception e)
          // Your exception handling
        finally
          // Close all your resources
    public class DataBuffer
      protected LinkedList dataList;
      protected boolean finished;
      public DataBuffer()
        dataList = new LinkedList();
        finished = false;
      public synchronized void bufferData(Object data)
        dataList.add(data);
        notifyAll(); // let anyone that's waiting for data know that some has arrived
      public synchronized Object waitForData() throws InterruptedException, IllegalStateException
        if(finished)
          throw new IllegalStateException("Buffer is finished");
        // If we can't return anything at this moment then get this thread to wait until another
        // thread puts something into the buffer
        if(dataList.empty())
          wait();
          if(dataList.empty()) // Usually caused by setFinished being called
            throw new IllegalStateException("Buffer is finished");
        return dataList.removeFirst();
      public boolean isFinished()
        return finished;
      public synchronized void setFinished(boolean finished)
        this.finished = finished;
        notifyAll(); // If someone's waiting then we should let them know that nothing's gonna happen
    public class ConsumerThread extends Thread
      protected DataBuffer buffer;
      public ConsumerThread(DataBuffer buffer)
        super("ConsumerThread");
        this.buffer = buffer;
      public void run()
        Object data;
        while(!buffer.isFinished())
          try
            data = buffer.waitForData();
          catch(Exception e)
            // Your exception handling code!
    }The code snippet uses synchronisation quite a bit to manage concurrent access to sensitive state.
    Just ask again if this doesn't make sense.
    Hope this helps.

  • Oracle Linux 6.3 and Oracle VM 3.0.3 : high "os thread startup" waits

    Hi all,
    we just installed Oracle Linux 6.3 as a PVM guest with Oracle VM 3.0.3.
    The vm is acting as a dbserver.
    We see high "os thread startup" wait times from statspack report. A 10-hour report shows:
    Top 5 Timed Events Avg %Total
    ~~~~~~~~~~~~~~~~~~ wait Call
    Event Waits Time (s) (ms) Time
    CPU time 13,819 57.5
    db file sequential read 1,839,279 5,791 3 24.1
    enq: TX - row lock contention 1 664 ###### 2.8
    os thread startup 1,350 451 334 1.9
    control file sequential read 166,312 386 2 1.6
    This seems to be an OS or virtualization issue: if i run some very simple commands like "ls " or "top", sometimes I see them hangig some seconds .
    What should I check for ?
    Thanks,
    Andrea

    This will sound silly, but: Make sure you aren't a victim of the "Some Linux machines have high CPU utilization after Leap Second insertion on July 1st". If your server was "doing NTP", this might have happened. You can google this, if you didn't hear of it. A reboot makes it go away.

  • Why do we need to take a lock before invoking wait()/notify() on an Objec

    Hi,
    Why do we need to take a lock before invoking wait()/notify() on an Object? i know that we shud take otherwise illegalstateexception is thrown.
    what is the reason to take a lock bfefore invoking the above methods. why does jvm expects from the programmer?
    Cheers,
    duggana.

    Well, very often a wait or notify is conditional on the state of some flag (semaphore) which is protected by the monitor. By putting the wait in a synchronized section you guarantee that the sempaphore won't change between the final test of it and the actual wait or notify, otherwise a notify might be lost and the program hang.
    // wait on semaphor
    if (!canProcede)
       synchronized(this)
           if(!canProcede)
              wait();
    //   release semaphor
    synchronized(this)
         if(!canProceed) {
              canProede = true;
              notify();
        }If the wait above wasn't guarded by the sychrozined it's possible the second code fragment might be executed between the test and the wait, in which case the wait would be called after the notify and, hence, wait for ever.

  • Why do we need to take a lock before invoking wait()/notify() on an Object?

    Hi,
    Why do we need to take a lock before invoking wait()/notify() on an Object? i know that we shud take otherwise illegalstateexception is thrown.
    what is the reason to take a lock bfefore invoking the above methods. why does jvm expects from the programmer?

    Please do not crosspost..

Maybe you are looking for

  • Goods receipt - Entry Door in WM

    Hello, i work in 4.7 environment and we are implementing task and resource management.  We have to map in our warehouse entry doors and staging area (bay) where the goods are temporarly stored before putaway. The doors must be assigned manually by  t

  • Can't see sync folder in LR

    I would like to keep current year picture files in the sync folder and be able to edit them in LR. However, it doesn't show under my folders list for LR. Is there a way to do this? Update: finally got this to work.

  • Iphoto pictures turn fuzzy

    I have my photos in iphoto and usually take them to imovie and make movie clips of them when I get enough. They look great in iPhoto and then when they show up in iMovie they are fuzzy and distorted any ideas? This is the first time I have tried this

  • ICloud is randomly deleting iCal entries

    At several points over the past week, I thought my calendar appeared unusually "thinned out". Then last night I noticed an appointment I had been delaying for a while was nowhere to be seen. At first I thought it may be somewhere on my calendar, a we

  • Issue while connecting BW query using BICS Connection

    Hi All, I have an Issue with Xcelsius while using the BICS connection .when i select the query from the BW System its throwing an Error #2032 . Can some one please help with a Solution. Regards, Raj