Sorry if this is basic, I just don’t see the answer. Basically I am running a few threads using ThreadPoolExecutor to launch 10 threads. I want each thread to make its own connection to a server for the duration of its life. Is it possible and if so where do I put this code?
Example code:
class DoWork implements Runnable{
protected String[] data = null;
public DoWork(String[] data) {
// get the data each thread needs to work
this.data = data;
}
public void run() {
// Do the work here
}
}
My understanding has been if there are items in the work queue then ThreadPoolExecutor keeps the 10 threads alive and when the work is done they die. Is there somewhere in this structure I can add connection information? I don’t want to do it in the DoWork method because that’ll be done for each work unit(thus opening connections for as many items in the work queue, could be thousands and causes timeouts when I tried). Putting in-between the class declaration and the method didn’t seem to do anything(although I could be doing it wrong).
Any ideas of how to accomplish this?
UPDATE: not 100% needed but I’m curious if there’s also a way to get it do something upon termination(maybe so I can close the connection to the server instead of waiting for it to timeout).
You could use a ThreadLocal to store the connection for each thread:
Or, if the connections can be used (at different times) by several threads, you could create a pool of connections. The run method would get a connection from the pool (which would dynamically create it and add it to the set of created connections is none is available), and release it to the pool (in a finally block) when it has finished using it. This would make the connection available for any other task. This would have the advantage of making the number of needed connections potentially lower than the number of threads in the thread pool.