Completion Service:
This is quite a nice java API that i came across. This is useful if you submit lots of future object and would like to get a callback when they are complete, regardless of the order. Alternative would have been to poll each future.
In one thread
completionservice.Submit()
in separate thread
completionService.take()
Ordered Executor
We had a scenario where we would get several messages related to one order and they need to be processed in order.
So solution was to have an array of single thread executors and we would submit each message for a given orderid to same executor. to accomplich that we would use method such as below
private ExecutorService getEcecutor(Object key){
if(numExecutors>1 &&key!=null){
int index=Math.abs(key.hashCode())%numExecutors;
return executorArray[index]
}else{
return executorArray[0]
}
}
Threads
waiting for another thread If
t
is a Thread
object whose thread is currently executing,t.join();
Interupts
use Thread.interrupted() to check if interrupt has been issues
When a thread checks for an interrupt by invoking the static method
Thread.interrupted
, interrupt status is cleared. The non-static isInterrupted
method, which is used by one thread to query the interrupt status of another, does not change the interrupt status flag.Producer/ consumer pattern
Use blocking queue which provide blocking put and take methods
Work stealing pattern
when the worker exhausts works from its own queue it can steal work from another works queue
Blocking QUEUE interface
methods are summarized in the following table:
Throws exception | Special value | Blocks | Times out | |
Insert | add(e) |
offer(e) |
put(e) |
offer(e, time, unit) |
Remove | remove() |
poll() |
take() |
poll(time, unit) |
Examine | element() |
peek() |
not applicable | not applicable |
LOCKS
public class Reentrant{ public synchronized outer(){ inner(); } public synchronized inner(){ //do something } }
If a thread already holds the lock on a monitor object, it has access to all blocks synchronized on the same monitor object. This is called reentrance.
details at IBM Blog
Volatile keyword in Java is used as an indicator to Java compiler and Thread that do not cache value of this variable and always read it from main memory.
Volatile keyword in Java is used as an indicator to Java compiler and Thread that do not cache value of this variable and always read it from main memory.