0

I need your help.

I got 2 JAVA classes. In one class there is a FIFO list/queue, both classes have to access this list concurrent. The list is in class1. Class1 uses the addElementToEndOfQueue. Class2 uses getValueOfQueue to get und remove the head of the queue.

public static synchronized String getValueOfQueue(){
    return queueSend.poll(); 
}

public synchronized boolean addValueToQueue(String s){
    Boolean blnReturn = queueSend.offer(s);
    class2.interrupt();
    return blnReturn;
}

Class2 tries and takes the head value of the queue, if the queue is null than strValue is null and the thread should wait till he is interrupted bei addValueToQueue:

while(true){
 String strValue = class1.getValueOfQueue();
 if (strValue == null) {
            try {
                wait();}
            catch (InterruptedException e) {
                continue;}
// do things
}

My problem is now that if have to wait/sleep in the while loop (to simulate a delay). If i use sleep or wait than it could happen that addValueToQueue interrupts me and I don't want that. I want the programm to wait the given time and not be interrupted. How can I do this? Or should I use a completely other approach as I am using right now? Thanks for your help!

Tim
  • 193
  • 4
  • 15
  • 3
    Have you looked at `java.util.concurrent.BlockingQueue`? http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingQueue.html It may solve your problem without the need to synchronize it yourself. – Alexander Tokarev Jan 30 '14 at 11:53
  • 1
    You should be using wait() and notify(), not sleep() and interrupt(). This is exactly what they're for. – user207421 Jan 30 '14 at 12:23
  • Another side comment: be prepared for [spurious wakeups](http://stackoverflow.com/questions/1050592/do-spurious-wakeups-actually-happen) in those situations. – rlegendi Jan 30 '14 at 12:31
  • @EJP what can I wait for? I should wait for getValueOfQueue() returns a value != null but how can I do that? – Tim Jan 30 '14 at 12:37

0 Answers0