Search code examples
javamultithreadingactivejdbc

Execute a resource liberation action on Java's ThreadPoolExecutor's Thread death


I have a Java ThreadPool that is initialized as follows:

ThreadFactory tFactory = new DatabaseWorkerThreadFactory();
final ExecutorService dbService = new ThreadPoolExecutor(1, 5, 10L, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10), tFactory);

Then execute Runnable Task on that threadpool like this

executorService.execute(new RunnableDbInsertTask(netData));

to get those inserts to be async from the rest of my code.

As i'm using ActiveJDBC as an ActiveRecord implementation, I need each worker to have an active Connection, which I do having this code at the start of the RunnableDbInsertTask's run() method:

if(!Base.hasConnection())
        Base.open(params);

So when the ThreadPoolExecutor is used, each new spawned Thread that gets tasks, will have a unique connection, and will reuse it for every connection.

Now I want the thread amount to fallback to the minimum (1), as specified in the ThreadPoolExecutor's constructor, when there are no jobs to be done.

For this to happen correctly, I need that when a Thread is automatically finished by the ThreadPoolExecutor because of inactivity, it auto-finishes it's connection calling ActiveJDBC's Base.close() method

As a solution I tried overriding DatabaseWorker.interrupt() method, but that didn't worked.

Any help appreciated. Thanks!


Solution

  • I think you should not rely on the executor to open and close your connections. Instead of opening direct connections to the DB, you need to use a pool of connections and open a connection from the pool. Also, at the end of your run() method, you must close the connection. Since these are polled connections, a real JDBC connection will simply go back to the pool instead of closing. Here is the preudo-code:

    public void run() {        
        try {
            Base.open("myConnectionJNDIName");
            //do some real work here
        } finally {
            Base.close();//always close connection
        }
    }
    

    This way you have more control over thread count vs connection count.