Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proving the following code not thread safe

How can I quickly prove that the following class is not thread-safe (as it uses Lazy Initialization and not using synchronization) by writing some code ? In other words, if I am testing the following class for thread safety, how can I fail it?

public class LazyInitRace {
  private ExpensiveObject instance = null;

  public ExpensiveObject getInstance() {
     if (instance == null)
        instance = new ExpensiveObject();
    return instance;
  }
}
like image 394
Lydon Ch Avatar asked Mar 09 '10 16:03

Lydon Ch


People also ask

How do I know if a code is thread-safe?

How do we know if code is thread-safe? We can tell that code is thread-safe if it only uses and updates shared resources in a way that guarantees safe execution by multiple threads at the same time. Shared resources can be a counter variable, an array, or anything else.

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.

Which class is not a thread-safe?

When designing a class that may be used for concurrent programming—that is, a class whose instances may be used by more than one thread at a time—it is imperative that you make sure the class is " thread-safe.” Consider the IntList class of Example 2-7. This class is not thread safe.

How do you prove a Hashmap is not thread-safe?

Very Simple Solution to prove this We can see that it prints the keys which are not in map, even though we have put the same key in map before doing get operation. Its strange to see the values printed, that's why hashmap is not thread safe implementation working in concurrent environment.


1 Answers

By definition, race conditions cannot be tested deterministically, unless you control the thread scheduler (which you don't). The closest thing you can do is either to add a configurable delay in the getInstance() method, or write code where the problem might manifest and run it thousands of times in a loop.

BTW, none of this really constitutes "proof". Formal Verification would, but is very, very hard to do, even for relatively small amounts of code.

like image 127
Michael Borgwardt Avatar answered Oct 16 '22 06:10

Michael Borgwardt