My question involves stopping a thread within an executor's fixed thread pool. Currently, I have
a small server which genereates a new 'client device' thread each time someone connects. The new
thread is started within the executor and everything seems to be working fine there, however when
someone disconnects I am having issues ending that thread. I'll attach the two classes involved here
so you can see what I am trying to do. Essentially I need to close and thread (so it can be used by
another client) whenenver someone disconnects...however I can't figure how to go about this.
Right now I have it set up to where a synchronized array list is keeping track of the clients
currenly connected. I realize that this may not be necessary since the fixed thread pool is also
holding all of the clients' threads, I'm just using it to keep the GUI updated. I feel like there
is some block of thread pool knowledge that I'm missing, but the API doesn't seem to list any methods
for ending a single thread within a pool, only the pool itself, which isn't what I need.
FYI: the only reason that MAX_CONNECTIONS_ALLOWED is set to 1 is for testing purposes.
. Essentially I need to close and thread (so it can be used by another client) whenenver someone disconnects...however I can't figure how to go about this.
You should not (and can not) directly manage (control, shutdown, etc..) pool's threads. When you job completes, the thread automatically became available for other jobs. In your case you ClientDevice.run method should terminate at some time. If it is terminated when IOException is thrown, then all is fine. Thread will be available for other jobs after the run method completes.
Some more complex executors may terminate unused threads, but they also do not provide an API to manually terminate any thread.
I think I understood your problem, you want to cancel/stop a thread that you know that something is wrong, right? AFAIK the Java API doesn't have that, it would required you to do some workaround to archive that feature, for example I would suggest you to create a implementation of ThreadFactory (http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadFactory.html) to you have the references of the threads created by the Executor then you just need to check which thread the runnable is in (using the thread name set earlier e.g.) .