Search code examples
javamultithreadingthread-safetysynchronized-block

Is a method thread-safe if the return value is declared/returned outside of a synchronized block?


public Foo getFoo(){
    Foo foo = null;

    synchronized(fooList){
        if(fooList.size() > 0){
            foo = fooList.remove(0);
        }
    }

    return foo;
}

Since foo is declared outside of the synchronized block, does the potential exist of returning bad data?


Solution

  • Each thread instance calling getFoo() will have its own foo instance. Thus foo is thread safe and doesn't need synchronization.