I think creating a separate thread for each socket could end up being too many. Also, creating a new Thread
is kind of expensive in execution time. You should cap the number of active threads and limit new thread creation by using a thread pool. java.util.concurrent.Executors
offers the ability to create a fixed thread pool. Details in http://java.sun.com/docs/books/tutorial/essential/concurrency/pools.html .
If it's sockets you want to protect from being hit by multiple threads at one time, I'd consider the very simplest exclusion: Locking on the socket object. There could be more efficient strategies but probably none simpler or more foolproof.
Update
If another selection is done while some of the earlier returned sockets are still in processing, you could end up with threads interfering with each other. Shutting other threads out via locking is possible but not really an elegant solution (sorry).
Two alternatives I can think of:
deregister the channel before starting your processing thread on it, and re-register it at the end of the processing activity. Sounds klutzy but should get the job done.
maintain your own data structure of in-progress channels, e.g. a Set
, and add a newly found-ready channel to that set before giving it to a thread, and remove it before returning from the thread. When processing channels from the selection set, ignore any that are already in the set. All use of this set will need to be synchronized.