How to split an object between two threads (thread synchronization)?

I have two threads. One writes audio data to a variable. Another thread sends this recorded variable to the server. What do I need to do in terms of concurrency since I'm new to multithreading?

The following is a snippet of code:

short[] sData = new short[1024]; recordingThread = new Thread(new Runnable() { public void run() { android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO); while (isRecording) { recorder.read(sData, 0, BufferElements2Rec); } } }, "AudioRecorder Thread"); recordingThread.start(); 

and another thread that accesses the same sData and sends it to the server:

 Thread sendThread= new Thread(new Runnable() { public void run() { android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO); while (true) { try { ByteBuffer.wrap(bData).order(ByteOrder.LITTLE_ENDIAN) .asShortBuffer().put(sData); } } }); 
+4
source share
3 answers

There are two aspects to your question.

  • Assuming sData is a local variable, all you have to do to get two streams to share the array is to declare sData as final . (And if sData is an instance or class variable, you don't even need this ...)

  • Getting two streams to share an array safely is a little more complicated. The problem is that these two threads need to be synchronized. The send stream must know how much of the array the write stream is writing. In addition, synchronization is necessary to ensure that data recorded by the write stream is visible in the send stream.

In this example, proper synchronization is likely to entail a couple of additional variables to indicate the current positions of the two streams. And since you have to deal with cases where one thread needs to wait for someone to add or send data, you probably have to use Object.wait() and Object.notify() to avoid waiting for a wait.


But what you do on a semantic level looks like it should work like a classic circular buffer of short values. Therefore, I would recommend looking for an existing implementation that you can reuse. (For example, if you are ready to take the short overhead against short , then you can use ArrayBlockingQueue<Short> .)

+2
source

To minimize wheel reuse, you can implement it as a manufacturer / consumer synchronization. For beginners:

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/ArrayBlockingQueue.html

Just in case, some introductory materials are here:

http://en.wikipedia.org/wiki/Producer-consumer_problem

+3
source

One way to handle this is to use latch if it is a one-time operation or CyclicBarrier if it needs to be repeated.

0
source

All Articles