Mahendran
Mahendran

Reputation: 2243

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.

Upvotes: 4

Views: 1262

Answers (3)

Gray
Gray

Reputation: 116908

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.

Upvotes: 6

Bernhard Barker
Bernhard Barker

Reputation: 55619

No, if you create a new instance of UnSafeSequence in run each thread will have its own value member and this will not show a problem. You have 2 options:

  • Make value and getNext() static and call it with UnSafeSequence.getNext()

  • Create a shared object and pass it to your threads upon creation

    class MyThread implemented Runnable
    {
       UnSafeSequence unsafe;
       MyThread(UnSafeSequence unsafe) { this.unsafe = unsafe; }
       public void run() { /* call unsafe.getNext(); */ }
    }
    

Upvotes: 2

i_am_jorf
i_am_jorf

Reputation: 54610

You can create a single UnSafeSequence instance per thread, and that will be completely safe. If you do that for N threads, you will have N copies of value, which is the non-synchronized data in question.

If you want to access it in a thread unsafe manner, you need to create a single instance of UnSafeSequence and then call getNext() from multiple threads.

Upvotes: 0

Related Questions