0

I have a nested assignment inside a while loop which gives me unexpected results. The code below is running in a thread that writes package data to file. The packages are recieved from another thread through a ConcurrentLinkedQueue.

This code never enters the write section for as long as the producer is putting packages in the queue.

Packet packet = null;
while (!done || (packet = queue.poll()) != null){
    if (packet != null){
        packet.write(bufferedOutputStream);
    }
    else{
        Thread.sleep(100);
    }
}

However, this code does enter the write section as soon as there is a packet in the queue. This is for me the expected behaviour.

Packet packet = null;
while (!done || packet != null){
    packet = queue.poll();
    if (packet != null){
        packet.write(bufferedOutputStream);
    }
    else{
        Thread.sleep(100);
    }
}

Is there something I am missing out on? Why are these code snippets producing different results?

Andreas
  • 96
  • 8

1 Answers1

6
while (!done || (packet = queue.poll()) != null){
    ...

|| is short-circuited. That means that if the first operand is true, the second is not evaluated.

For this code, that means that if done is false, (packet = queue.poll()) != null will not be evaluated, so packet will not be reassigned.

khelwood
  • 55,782
  • 14
  • 81
  • 108