Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this code not thread safe?

Tags:

java

scjp

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();
    }
}
like image 912
blue-sky Avatar asked Nov 25 '11 11:11

blue-sky


People also ask

What happens if code is not thread-safe?

Conditionally safe: Different threads can access different objects simultaneously, and access to shared data is protected from race conditions. Not thread safe: Data structures should not be accessed simultaneously by different threads.

Why is Python not thread-safe?

Python is not thread-safe, and was originally designed with something called the GIL, or Global Interpreter Lock, that ensures processes are executed serially on a computer's CPU. On the surface, this means Python programs cannot support multiprocessing.

Why are lists not thread-safe?

Being thread-safe would mean that any operation modifying the list would need to be interlocked against simultaneous access. This would be necessary even for those lists that will only ever be used by a single thread. That would be very inefficient. Save this answer.


2 Answers

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...

like image 196
Jon Skeet Avatar answered Oct 22 '22 18:10

Jon Skeet


I think if the method is not static, each TestSeven object would synchronize using its own lock - so there will be one thread per lock, and none of them will have to wait for another thread. If the method is declared static, I seem to recall they lock on the corresponding Class object.

like image 30
Vlad Avatar answered Oct 22 '22 18:10

Vlad