Breaking News: Grepper is joining You.com. Read the official announcement!
Check it out

Check if following code is threadsafe for retrieving an integer value from a Queue?

Pragya Keshap answered on February 4, 2023 Popularity 1/10 Helpfulness 1/10

Contents


More Related Answers

  • opération inter-threads non valide

  • Check if following code is threadsafe for retrieving an integer value from a Queue?

    0

    public class QueueCheck {

    Queue queue;

    public Integer getNextInt() {

    Integer retVal = null;

    synchronized (queue) {

    try {

    while (queue.isEmpty()) {

    queue.wait();

    }

    } catch (InterruptedException e) {

    e.printStackTrace();

    }

    }

    synchronized (queue) {

    retVal = queue.poll();

    if (retVal == null) {

    System.err.println("retVal is null");

    throw new IllegalStateException(); }

    }

    return retVal;

    }

    }

    In the above code Queue is used as object monitor to handle

    concurrency issues. But it may not behave correctly in a multithreading scenario.

    There are two separate synchronized blocks in above code. In case

    two threads are woken up simultaneously by another thread, both

    threads will enter one after in the second synchronized block.

    Only one of the two threads will get new value from the queue and

    make it empty. The second thread will poll on an empty queue and it

    will not get any non-null return value.

    https://www.geeksforgeeks.org/thread-safety-and-how-to-achieve-it-in-java/

    Popularity 1/10 Helpfulness 1/10 Language java
    Source: Grepper
    Tags: integer java
    Link to this answer
    Share Copy Link
    Contributed on Feb 04 2023
    Pragya Keshap
    0 Answers  Avg Quality 2/10


    X

    Continue with Google

    By continuing, I agree that I have read and agree to Greppers's Terms of Service and Privacy Policy.
    X
    Grepper Account Login Required

    Oops, You will need to install Grepper and log-in to perform this action.