I’m reading a Bluetooth data stream on a background thread and passing that data to the UiThread for processing and display via a Message Handler. A more detailed description of the process can be found here.
Currently I’m reading the InputStream to a byte[] and using Handler.obtainMessage() to get a message with the byte array as an object arguement.
I ran into a problem with packets overwriting each other because the array is not locked across threads and is being overwritten in the background before the UiThread can process it. The obvious solution is to copy the array to a new array and pass that new object.
The problem is this is very expensive on Android and I am going to be getting a fairly continuous stream of data. Is there a better way to pass this data to the main UiThread?
Perhaps by synchronizing the byte array or a more memory efficient way of copying the array?
It sounds like what you want to is pool of byte arrays that you can check out for use and check in when finished with. An implementation might look like
Disclaimer: I haven’t actually tested or even compiled this code, its just meant to convey the basic idea.
With this you hopefully have the minimum number of byte[] objects allocated at any given time. Ideally you also want to add in some code to reduce the pool size if for some reason it expanded a bunch and now required pool size is smaller.
Personally I think you might be worrying a little too much about micro-optimizations before its clear whether you need it or not. (Or maybe you’ve already profiled your application and know that you need it.)
UPDATE: Hackbod’s solution is actually more efficient than the one I suggested, although it still possibly suffers from having too many objects in the pool.