Search code examples
javaservletsasynchronoussynchronizedvolatile

Java synchronize asynchronous calls from JavaScript


I have a lot of asynchronous GET calls from the client and one POST request. After my servlet got the POST request I would like to handle the oncoming GET calls in an other way. Here is what I tried but failed:

public class MyServlet {

    private static volatile proceed = true;

    public void doGet(req, resp) {
        ...
        doGetAnswer(req, resp);
        ...
    }

    public void doPost(req, resp) {
        ...
        doPostAnswer(req, resp);
        ...
    }

    public String doGetAnswer(req, resp) {
        if (proceed)
            return "Answer GET request";
        else
            return "Do NOT answer GET request";
    }

    public String doPostAnswer(req, resp) {
        proceed = false;
        return "POST called, stopping GET requests";
    }
}

My problem is that the threads that are running by a GET call do not recognize the change of the volatile variable.


Solution

  • Very uncommon design...

    Anyway, when you have concurrent read/write of a primitive type variable, you may want to use Atomic* datatype.

    AtomicBoolean shall do the trick:

    Replace volatile proceed = true by AtomicBoolean proceed = new AtomicBoolean(true)

    Replace if (proceed) by if (proceed.get())

    Replace proceed = false; by proceed.set(false)