How to demonstrate that a class isn't thread safe

Viewed 98

I am kinda new to threads. How can I prove, by writing code in a separate class, that MyClass class isn't thread safe? I've been searching but I can't really find an example to aid me.

public class MyClass {
  private static int value = 0;
  
  public static void set(int setVal) {
    value = setVal;
  }

  public static int get() {
    return value;
  }  

  public static void decrement() {
    int temp = value;
    value = --temp;
  }
}
1 Answers
public static void main(String[] args) {
    int nt = 10;
    int c = 20000;

    MyClass.set(c);

    Thread[] threads = new Thread[nt];

    for (int t = 0; t < nt; t++) {
        Thread thread = new Thread(() -> {
            for (int i = 0; i < c; i += nt) {
                MyClass.decrement();
            }
        });
        thread.start();
        threads[t] = thread;
    }

    try {
        for (Thread thread : threads) {
            thread.join();
        }
    } catch (Throwable tr) {
        tr.printStackTrace();
    }

    System.out.println(MyClass.get());
}

Try this. If you add synchronized to the decrement method of MyClass it will print out 0 (thread safe), but if you don't synchronize decrement than it will print out a wrong number.

This proves that MyClass (its decrement method) is not thread prove, since if it was it would print out 0.

Also, if you can't use lambdas than replace the first for loop with the following:

for (int t = 0; t < nt; t++) {
    Thread thread = new Thread(() -> {
        for (int i = 0; i < c; i += nt) {
            MyClass.decrement();
        }
    });
    thread.start();
    threads[t] = thread;
}

Hope I could help!

Related