0

public class A {}

// 1. suppose Test is definitely a singleton, here skip singleton default impl

// 2. Test field a (class A) has no dirty value issue, or does it?

// 3. Singleton Object (ex, this sample) field assignment (in multi-threaded environment), has no race condition or deadlock issue, or does it?

public class Test
{

    private A a;

    public A get() {
        if (a == null) {
            a = new A();
        }
        return a;
    }
}
nullptr
  • 3,320
  • 7
  • 35
  • 68
jiangyan
  • 28
  • 1
  • 1
    There's no deadlock, but it's absolutely not thread-safe. You could easily end up with multiple instances being created. – Jon Skeet Nov 04 '14 at 17:48

1 Answers1

4

Your code is not thread safe.

Suppose

  1. Thread 1 called Test.get()
  2. Thread 1 get() method checked (a == null) -> which is true
  3. ---Context Switch Here---
  4. Thread 2 called test.get()
  5. Thread 2 get() method checked (a == null) -> which is true
  6. Thread 2 get() method creates an A1 object and assigns it to a;
  7. Thread 2 get() method returns A1
  8. ---Context Switch Here---
  9. Thread 1 get() method creates an A2 object and assigns it to a;
  10. Thread 1 get() method returns A2

this means that two different threads got two different instances of class A

Hope this helps

Ozan Tabak
  • 662
  • 3
  • 9