Unusual Java behavior - why does this work?

Viewed 552

I've found some interesting behavior... I can't decide if it's a bug or incompetence, but currently leaning towards incompetence.

This code will not enter the loop, even if there are messages waiting:

Message msg;
while ((msg = consumer.receiveNoWait()) != null) {
    System.out.println(msg);
}

This code DOES enter the loop, notice the null assignment:

Message msg = null;
while ((msg = consumer.receiveNoWait()) != null) {
    System.out.println(msg);
}

This code is running on Glassfish 3.1.1b10 HotSpot 1.6_26 on Windows 32bit. I can't think of an explanation why the first block doesn't work!

EDIT/UPDATE July 13, 2011:

First, I began stopping the Glassfish domain and deleting it between deploys per request, and this still occurs :)

Second, I cannot sync on Destination or Consumer, as this is Java EE code. But, I can assure there are messages available. There's about 500 of them available an no consumers. In fact, creating a QueueBrowser tells me there's messages available!

Third, this program prints "WORKS!" every time!!! ARGH!!!

public static void main(String[] args) {
    Object obj;

    if ((obj = getNotNull()) != null) {
        System.out.println("worked!");
    } else {
        System.out.println("failed!");
    }
}

static Object getNotNull() {
    return new Object();
}

Lastly, I was speaking about my own incompetence. ;)

4 Answers
Related