1

I got a Queue in my Server class:

public class Server{

    Queue<Input> inputQueue; 

    public void start() {
      inThread = new InThread(inputQueue);
      outThread = new OutThread(inputQueue);

      inThread.start();
      outThread.start();
    }
}

The inThread will responsible for fill in data in the inputQueue, and the outThread will responsible for take out data from the outputQueue. InThread and OutThread will execute concurrently. Will there a chance that the data will not thread safe? If so, I did some study, it have synchronized variable and synchronized method. Which one should I use? Thanks.

DNB5brims
  • 29,344
  • 50
  • 131
  • 195

4 Answers4

0

As the queue is shared between threads so it is not thread safe without sunchronizing your read and write methods.

If you want a thread safe queue readymade then you may consider using ConcurrentLinkedQueue:

http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ConcurrentLinkedQueue.html

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
0

There isn't much of a need for hand-synchronization, although your existing approach is not threadsafe.

java.util.concurrent.ArrayBlockingQueue<E> can work for you. Its constructor allows one to pass in a collection, so you can do:

ArrayBlockingQueue<Input>blockingQueue=new ArrayBlockingQueue<>(128, false, inputQueue);

changing 128 as the capacity and the boolean as specifying whether queueing after blocks should be fair.

You can also use ConcurrentLinkedQueue. Its constructor is just:

ConcurrentLinkedQueue<Input> clq=new ConcurrentLinkedQueue<>(inputQueue);
nanofarad
  • 40,330
  • 4
  • 86
  • 117
0

I would use an ExecutorService which wraps a thread pool and a Queue and is thread safe/tested/is written for you.

You are right that some Queues require external synchronization but if you use a thread safe collection like ConcurrentLinkedQueue you don't need synchronized, though it won't hurt much if you do.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

To me Your question seems to be the case of standard producer consumer case with Wait and Notify .

Just google producer consumer example in java , you will get thousands of examples.Hope it helps.

M Sach
  • 33,416
  • 76
  • 221
  • 314