Blocking Queue Take out of Order

38
April 22, 2019, at 6:00 PM

I have a simple blocking queue containing Integers. In a multi thread environment I am taking and adding elements to the the back of the queue.

BlockingQueue<Integer> test = new LinkedBlockingQueue<Integer>();

The goal is to have adding in order.. and taking be in the same order as well. On the 5th line of my program output, 3 is somehow at the front of the queue before 2 is, despite it appearing that 2 was added first. All of these were added in a single threaded environment, so I know the code to be added is executed in order

 Add: 1
    Add: 2
    Add: 3
    Take: 1
    Take: 3
    Add: 4
    Take: 2
    Take: 4

Is this unexpected behavior? Right now I am only tested in Single Threaded environments so I would expect the de-queing order to stay consistend with the order that was added.

Is there another thread safe datastructure that I should be using instead?

Thanks for the help in advance

Answer 1

You need to ensure taking and printing is an atomic operation without this you can have

T1: take a number say 1
T2: take a number say 2
T2: print a number 2
T1: print a number 1

i.e. unless you ensure printing is in the order you take the values, it can be in any order.

Printing using a lock on System.out so you can use this to make it atomic

synchronized (System.out) {
    Integer task = queue.take();
    // no chance of a race condition here.
    System.out.println("took " + task);
}
READ ALSO
WebServiceContext is coming as NULL in WAS 9.0.0.9

WebServiceContext is coming as NULL in WAS 9.0.0.9

I have created an web-service using JAX-WS and WAS 90

23
Is there a way to attach JSON Web Tokens to an HTML form POST request?

Is there a way to attach JSON Web Tokens to an HTML form POST request?

I'm building a blog using nodejs (no Express) where users can comment on posts

56
Execute SQL query on HTML form element ( Dropdown ) onchange event

Execute SQL query on HTML form element ( Dropdown ) onchange event

I have trying to execute SQL query when we change the dropdown valuesSince we can't execute it using JavaScript , How can we do that

29
Position of div children get wrong because of scale transform on div parent

Position of div children get wrong because of scale transform on div parent

I'm working on a react app where there is two columns face to face, each columns has rows insideEach rows of differents columns can be connect by one or many lines

51