Search code examples
javascjp

Why is this code not thread safe?


In code snippet below, declaring the doThings() method as static would make the class thread-safe. Is the reason for this that if multiple TestSeven threads are started and since x is a static variable a race condition could occur ?

public class TestSeven extends Thread{

    private static int x;

    public synchronized void doThings(){
        int current = x;
        current++;
        x = current;
    }

    public void run(){
        doThings();
    }

    public static void main(String args[]){
        TestSeven t = new TestSeven();
        Thread thread = new Thread(t);
        thread.start();
    }
}

Solution

  • Yes, exactly. The synchronized nature of doThings only stops it from being called by multiple threads concurrently on the same instance. The variable x is shared on a global basis, not on a per-instance basis, therefore it's unsafe.

    In real world terms, think of it as a bathroom with several doors - someone can open one door and then lock it, but that doesn't stop someone else from coming in via a different door...