views:

52

answers:

4

Hi, I have the following code that retrieves the first element off a queue only if it has at least 2 elements. For some reason, it's not polling the first element. However, if I add a print statement in there, it will print and poll. The method is in a thread, and there's another thread adding element to the queue, this thread reads from the queue.

...
public void run(){
    while(beginning){
        int size = queue.size();
        // adding this will cause the program to enter if below: System.out.println(size);
        if(size > 1){
            System.out.println("data: " + queue.poll());
            beginning = false;
        }
    }
}
...

If the println statement is added, it will print
1
1
....
2
data: data

If the println statement is remove, it will not print anything.

Actually, as long as I put something in there, a thread.sleep(1) or a random print statement, it will poll out the data and print it

Thanx for any input.

A: 

It looks like a synchronization issue.

Dheeraj Joshi
A: 

You should be careful about using a shared resource between threads. You should consider to use a lock ( token ) , acquire it before accessing the queue and releasing it after use.

Jorge Niedbalski R.
A: 

You need to synchronize on the queue object:

public void run(){ 
    while(beginning){ 
        synchronized (queue) {
            int size = queue.size(); 
            // adding this will cause the program to enter if below: System.out.println(size); 
            if(size > 1){ 
                System.out.println("data: " + queue.poll()); 
                beginning = false; 
            } 
        } 
    }
} 

This will prevent your multiple threads from accessing the queue at the improper times.

You will also have to synchronize the thread that is adding items to the queue in a similar way.

Starkey
A: 

... turned out that I have to synchronized on the thread to make it work because the queue is implemented by a linkedlist.

But why would a print statement make it work?