Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test a Non Thread safe class?

I am new to Threads. I am reading Java Concurrency in Practice. I found the following example in the book.

@NotThreadSafe
public class UnSafeSequence
{
     private int value;
     public int getNext()
     {
         return value++;
     }
}

I wanted to test this code by writing couple of threads(or more) accessing this class to get a feeling of thread safety.

I tried like these, but not sure really how to test these examples.

class MyThread implemented Runnable
{
    public void run()
    {
        //Should I create a new object for UnSafeSequence here ?
    }
}

Thanks for your help.

like image 994
Mahendran Avatar asked Feb 18 '23 10:02

Mahendran


1 Answers

I wanted to test this code by writing couple of threads(or more) accessing this class to get a feeling of thread safety.

If each thread has its own instance of UnSafeSequence then it won't demonstrate the problem. What you need to do is to create an instance of UnSafeSequence outside of your MyThread instances and pass it into the constructor of each MyThread.

 UnSafeSequence unsafe = new UnSafeSequence();
 ...
 new Thread(new MyThread(unsafe)).start();
 new Thread(new MyThread(unsafe)).start();
 ...
 class MyThread implemented Runnable {
       private UnSafeSequence unsafe;
       public MyThread(UnSafeSequence unsafe) {
            this.unsafe = unsafe;
       }
       public void run() {
            ...
            unsafe.getNext();
            ...
       }
 }

While you are learning about threads, be sure to read about the ExecutorService and other great classes. Here's a good tutorial from Sun^H^H^H Oracle.

like image 153
Gray Avatar answered Feb 20 '23 12:02

Gray