Concurrent Programming Fundamentals— Thread Safety

How to make Thread-Safe Code in Java

Example of Non-Thread-Safe Code in Java

public class NumberCounter {
private int count;
AtomicInteger atomicCount = new AtomicInteger( 0 );
public synchronized int getCount(){
return count++;
}
public int getCountAtomically(){
return atomicCount.incrementAndGet();
}
}
public class BasicObservableClass {   public interface Observer {
void onObservableChanged();
}
private Set<Observer> mObservers; public void registerObserver(Observer observer) { if (observer == null) {
return;
}
if (mObservers == null) {
mObservers = new HashSet<>(1);
}
mObservers.add(observer); } public void unregisterObserver(Observer observer) { if (mObservers != null && observer != null) {
mObservers.remove(observer);
}
}
private void notifyObservers() {
if (mObservers == null) {
return;
}
for (Observer observer : mObservers) {
observer.onObservableChanged();
}
}
}

What can happen if we use non thread-safe implementation in multi-threaded environment:

  1. Thread A invokes registerObserver(Observer)
  2. Thread A executes mObservers == null check and proceeds to instantiation of a new set
  3. before Thread A got a chance to create a new set, OS suspended it and resumed execution of Thread B
  4. Thread B executes steps 1 and 2 above
  5. since Thread A hasn’t instantiated the set yet, Thread B instantiates a new set and stores a reference to it in mObservers
  6. Thread B adds an observer to the newly created set
  7. at some point OS resumes execution of Thread A (which was suspended right before instantiation of a new set)
  8. Thread A instantiates a new set and overrides the reference in mObservers
  9. Thread A adds an observer to the newly created set

How to make Thread-Safe code in Java

public class NumberCounter {  private int count;
AtomicInteger atomicCount = new AtomicInteger( 0 );
public synchronized int getCount(){
return count++;
}
public int getCountAtomically(){
return atomicCount.incrementAndGet();
}
}

Important points about Thread-Safety in Java

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store