Question

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?

Was it helpful?

Solution

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

OTHER TIPS

What does "bad data" mean in this context? fooList may change asynchronously before synchronized(fooList) and after the corresponding closing brace, before return foo; (more generally speaking, up to the moment the returned value is used.) What is your ultimate goal?

getFoo will not return stale data, since Foo foo is local variable AND fooList is synchronized

Local variable is thread safe since each thread call will create a new Foo object, instead of sharing single object. While instead variable is not thread safe, since multiple threads can access fooList, but in this case the fooList is already synchronized.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top