I have a callback which receives an object. I make a copy of this object, and I must pass it on to another thread for further processing. It’s very important for the callback to return as fast as possible. Ideally, the callback will write the copy to some sort of lock-free container.
I only have the callback called from a single thread and one processing thread.
I only need to pass a bunch of doubles to the other thread, and I know the maximum number of doubles (around 40).
Any ideas? I’m not very familiar with Java, so I don’t know the usual ways to pass stuff between threads.
If this is just a one-off thing – you get the 40- or so doubles, and want to start a new thread processing that, then you can do it like this:
If this is something that happens often, then you will need to look into thread pools and use a java.utils.concurrent.BlockingQueue. Despite the name, the queue will only block if it becomes full.
You can create an array of doubles the appropriate size which your callback method puts into the queue. The put() operation is very quick and so your callback method will not be delayed for long. (unless the queue is full.)
Your other thread will use the take() method on the queue to get the object when an object is available. The take() method blocks until an object is available – if you don’t want that, but prefer to keep the thread running, doing other things, then use poll() instead.
One final thing to consider is – do you want just one worker thread handling the doubles from the callback, or do you want several? Having one thread makes sense when the work needs to be done one at a time – e.g. if you write the array to a file, there’s usually no point having multiple threads doing this. Buf if the work done on each array is independent, then it’s a good candidate for having multiple worker threads.