I am developing an Android application that opens a video stream using the class JavaCameraView, and captures frames from it. Then, my target is to realize a worker thread that saves these frames into a buffer, and another thread that takes every frame from the buffer, in order to process it with image-processing techniques. So the buffer is a resource shared between these two worker threads, that should run simultaneosly, so filling and emptying the buffer at the same time. I thought to realize the buffer as a ConcurrentLinkedQueue, and the two threads are realized implementing the Runnable interface. Then, in the Main Activity, I declare them, I istantiate them, and then I start them, but it seems that only the first becomes running, and the second never starts. I post here my code:
1)Buffer.java
public class Buffer {
private ConcurrentLinkedQueue<Mat> MyBuffer = new ConcurrentLinkedQueue<Mat>();
private static final String TAG = "MyBufferClass :: ";
private int index = 1;
public Buffer(){
Log.d(TAG,"Buffer Created");
}
public void insertElementInTail(Mat element){
MyBuffer.offer(element);
}
public Mat retrieveElementInHead(){
synchronized (MyBuffer){
if(!MyBuffer.isEmpty()){
return MyBuffer.peek();
}else{
return null;
}
}
}
public Mat removeElementInHead(){
synchronized (MyBuffer){
if(!MyBuffer.isEmpty()){
return MyBuffer.poll();
}else{
return null;
}
}
}
public int getSize(){
return MyBuffer.size();
}
}
2)SaveInBuffer.java
public class SaveInBuffer implements Runnable {
private Handler myHandler;
private Buffer myBuffer;
public Handler myThreadHandler;
MainActivity mainActivity;
Handler mainHandler;
int what = -1;
public SaveInBuffer(Buffer myBuf, MainActivity mainActivity){
//super("SaveInBuffer");
this.myBuffer = myBuf;
this.mainActivity = mainActivity;
this.mainHandler = mainActivity.mainHandler;
}
@Override
public void run(){
Looper.prepare();
myThreadHandler = new Handler(){
public void handleMessage( Message msg ){
if(msg.what==4){
Mat returnedFrame = (Mat)msg.obj;
myBuffer.insertElementInTail(returnedFrame);
}
}
};
Looper.loop();
}
}
3)TakeFromBuffer.java
public class TakeFromBuffer implements Runnable{
public Handler consumerHandler;
private Buffer myBuffer;
public TakeFromBuffer(Buffer myBuffer){
this.myBuffer = myBuffer;
}
@Override
public void run(){
Looper.prepare();
Mat consumedFrame = myBuffer.removeElementInHead();
Looper.loop();
}
}
The buffer is created within the MainActivity, and then passed as parameter to the threads. The question is how to manage the Buffer as a shared resource, so implementing synchronization techniques, and how to start the two threads simultaneosly, because it's really important that they run at the same time.
How could I do? Any help would be very appreciated.