Search code examples
javaconcurrency

Concurrency handling correct?


Proxy will be called from multiple thread, and Proxy.setWorker() may be called at some time, does anyone know if below implementation will cause problem?

class Worker {
    void methodA() {
        ...
    }
    
    void methodB() {
        ...
    }
};

… and …

class Proxy {
    volatile Worker mWorker;
    final boolean cond= true;
    
    public void setWorker(Worker worker) {
        mWorker = worker;
    }
    void methodA() {
        if(cond)
            mWorker.methodA();
    }
    
    void methodB() {
        if(cond)
            mWorker.methodB();
    }       
}

Solution

  • You get a data race when there are 2 threads doing a read/write or write/write to the same field and these reads/writes are not ordered by the happens-before relation (so there is no happens-before edge between them).

    The 'worker' field is volatile, so there is a happens-before edge due to the volatile variable rule; hence, there is no data-race.

    I would make the 'cond' field final if possible to prevent confusion. If you would modify the 'cond' field, then your code could have a data-race unless you make it volatile.