educative.io

Simpler Thread Safety example

Thread Safety example. I have a simpler example that proves the class is not thread safe. There is actually no need to sleep


Type your question above this line.

Course: https://www.educative.io/collection/5307417243942912/5707702298738688
Lesson: https://www.educative.io/collection/page/5307417243942912/5707702298738688/5741031244955648

import java.util.Random;

class DemoThreadUnsafe {

    // We'll use this to randomly sleep our threads
    static Random random = new Random(System.currentTimeMillis());

    public static void main(String args[]) throws InterruptedException {

        // create object of unsafe counter
        ThreadUnsafeCounter badCounter = new ThreadUnsafeCounter();

        // setup thread1 to increment the badCounter 200 times
        Thread thread1 = new Thread(new Runnable() {

            @Override
            public void run() {
                for (int i = 0; i < 100000; i++) {
                    badCounter.increment();
                }
            }
        });

        // setup thread2 to decrement the badCounter 200 times
        Thread thread2 = new Thread(new Runnable() {

            @Override
            public void run() {
                for (int i = 0; i < 100000; i++) {
                    badCounter.decrement();
                }
            }
        });

        // run both threads
        thread1.start();
        thread2.start();

        // wait for t1 and t2 to complete.
        thread1.join();
        thread2.join();

        // print final value of counter
        badCounter.printFinalCounterValue();
    }
}

class ThreadUnsafeCounter {

    int count = 0;

    public void increment() {
        count++;
    }

    public void decrement() {
        count--;
    }

    void printFinalCounterValue() {
        System.out.println("counter is: " + count);
    }
}

Hi @srivatsavg
Yes, your solution shows that it ThreadUnSafe but forgot one thing which author said which is

We sleep the threads to give them a chance to run in a non-deterministic order.

sleep() method of thread is mostly used for the context switching which makes it behaviour more non-deterministic.

I hope I have answered your question. If there is still any query then please feel free to reach out us. Thanks.