I am engaging the following problems:
is it necessary to have a thread for each client socket?
No, as a matter of fact, I wouldn't even not recommend it. If it's a small project and you don't want to use any existing library, I would suggest you use the java.nio package and the SelectableChannels. With a so called selector you can easily monitor clients for incoming data in a non-blocking way.
Here are a few useful links:
Thanks BTW: sorry for confusing every one, it is a small project that only involve 5-10 classes.
There's definately nothing wrong with it. All higher level abstractions are based on sockets one way or another. Unless your project is sufficiently large there is no need to pull a series other frameworks/toolkit to perform the same job. Threads are cheap (and can even benefit from a multicore architecture), although using SelectableChannels
as @aioobe suggested is not a bad idea either.
When your projects require it, you can always learn about other inter-process communication methods (message passing, remote method invocaton etc., and its about 100 implementations) then.
You might however want to limit the number of threads you server use simultaneously. This can easily be achieved by claiming e.g., a semaphore of a size equal to the number of threads you want to serve. Another interesting thing to consider is using java thread pools to better reuse your resources.
What about using standards technology for solving this problem?
JMS topic A distribution mechanism for publishing messages that are delivered to multiple subscribers.
Tutorial
Others have mentioned that you can use the nio library to reduce the number of threads necessary. i just wanted to point out that your current example code will not work. you must use a thread per socket when using the standard io streams. the available()
method is pretty much useless (in general) and will not stop your control thread from blocking.