I need to pass a huge amount of data (raw bytes) between threads - listener thread and another thread that deals with the data manipulation. Whats the best and fastest way to do that?
As others have pointed out it really depends on the task you have. I would suggest using a Message. For example if one of your threads is a producer of said byte[] data and the other is the consumer you may have something of the sorts:
public class ProducerThread extends Thread{
byte[] data;
public void run(){
while (isRunning){
Looper.prepare();
data = someMethodToGetYourByteData();
Message dataToSend = Message.obtain();
Bundle bundle = new Bundle();
bundle.putByteArray("data", data);
dataToSend.setData(bundle);
if (ConsumerThread.mHandler!=null){
ConsumerThread.mHandler.sendMessage(dataToSend);
}
Looper.loop();
}
}
and your consumer thread:
public class ConsumerThread extends Thread{
public static Handler mHandler;
byte[] data;
public void run(){
while (running){
Looper.prepare();
mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
mHandler.obtainMessage();
data = msg.getData().getFloatArray("data");
doSomethingWithData(data);
};
}
Looper.loop();
}
Keep in mind though that this may not be the best pattern to use, as many elsewhere on SO point out that it is not the best idea to extend a Thread, but it generally depends on the use case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With