0
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?

user1329572
  • 6,176
  • 5
  • 29
  • 39

3 Answers3

5

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

Steve Kuo
  • 61,876
  • 75
  • 195
  • 257
1

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?

Alexander Pavlov
  • 31,598
  • 5
  • 67
  • 93
  • If this method returns `null`, then the logic is that the `fooList` is empty. I want to make sure that this method doesn't return `null` when `fooList` is not empty. – user1329572 Apr 19 '12 at 15:26
  • 1
    OK I get the point. If at the moment of locking the monitor for `fooList` it is not empty (and ALL accesses to `fooList` are synchronized on it!) then you will never get `null`. – Alexander Pavlov Apr 19 '12 at 15:28
1

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.

Pau Kiat Wee
  • 9,485
  • 42
  • 40