Sample code:
public class ThreadTest{
public static void main(String ...arg){
try{
ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
for(int i=0; i < noOfTask; i++){
executor.execute(new ImplRunnable(connectionPool.getConnection()));
}
executor.shutdown();
//Wait for all threads completion
executor.awaitTermination(100, TimeUnit.MICROSECONDS);
}catch(Exception e){
e.printStackTrace();
}finally{
//close database connections etc.
}
}
}
class ImplRunnable implements Runnable{
private Connection conn;
public ImplRunnable(Connection conn){
this.conn = conn;
}
public void run(){
try{
for(int i =0; i < 1000000; i++){
counts++;
}
}catch(Exception exception){
exception.printStackTrace();
}finally{
//close all open statements
try{
conn.close();
}catch(Exception exp){
exp.printStackTrace();
}
}
}
}
My system has 4 cores therefore the pool size is 4 and I have 10 tasks to do
The for loop is opening 10 threads but 4 threads are running at a time. But the problem is when a thread is completed processing it is going in waiting state for forever and not picking up next task for processing. What is wrong with the above code?
Please suggest…
It was my fault only when I was assigning a connection to the thread from Connection Pool then I was not closing it when thread is done with processing. When I closed connection at end of a thread then it started working and threads are properly being assigned for next tasks.