I have the next code:
Executor exe = Executors.newFixedThreadPool(20);
while (true) {
try {
exe.execute(new DispatcherThread(serverSocket.accept()));
continue;
} catch (SocketException sExcp) {
System.exit(-1);
} catch (Exception excp) {
System.exit(-1);
}
}
For each DispatcherThread
I create a connection to the database (it means I have 20 connections), what I need to know is how I can close the connection to the database when the thread is stopped or it stops or finishes its flow.
You cannot directly know when the thread is stopped, the closest thing you have is
Thread#isAlive
method but it may returnfalse
when therun
method in the thread has finished but the thread may not be stopped since the JVM cannot guarantee it. But if yourDispatcherThread
class implementsRunnable
interface then you can write the clean up at the bottom of therun
method.Skeleton code:
By the way, Thread suffix is not a good name for a class that technically is not a thread (because it doesn't extend from
Thread
). Instead, give a proper name according to what should do.You could close the thread-specific connection at the end of your
run()
method.A
finally
block would ensure that it happened however the run() method exited.