At the moment I have a project where we develop a Java Texas Holdem Application. Of course this Application is based on a client server socket system. I am saving all joined clients (I'm getting them with socketServer.accept()
method) in an ArrayList
. At the moment I make one thread for each joined client, which permanently checks if the client send any data to the server. My classmate told me it would be way better if I create one big Thread, that iterates through the whole Client ArrayList
and checks every Client inputstreamreader
. Should I trust him?
Asked
Active
Viewed 53 times
1

Broots Waymb
- 4,713
- 3
- 28
- 51

Alexander Ciupka
- 11
- 2
-
You can't have 1 thread reading from all sockets' input streams if you are using sockets that block, as the first read call will block until that client as sent data, meaning you will block the thread from reading from other streams. You could, however, switch to a non-blocking implenetation, then handle all read/writes on a single thread (even accepting connections on that same thread if you wanted). Check out [this answer](http://stackoverflow.com/a/24617983/2398375) – Vince Oct 06 '15 at 16:48
-
your english is good. to answer your question, lets pull from the movie quotes. do you trust him? what does your heart tell you? If the answer is yes then do it. if not then research / do both yours and his ways to build your confidence and prove your case. when in doubt trust code, not people. at least in the scope of being a developer – hubson bropa Oct 06 '15 at 16:51
-
Use netty http://netty.io/ – Ya Wang Oct 06 '15 at 16:51
-
thanks for your answer. i will take a look into netty.io – Alexander Ciupka Oct 06 '15 at 16:55
2 Answers
1
Creating a thread per Socket isn't a good idea if your application will have a lot of clients.
I'd recommend into looking into external libraries and how they handle their connonections. Example: http://netty.io/, https://mina.apache.org/

Reinard
- 3,624
- 10
- 43
- 61
-
thanks for your answer. i will take a look into those external libraries. – Alexander Ciupka Oct 06 '15 at 16:55
1
Both approaches are not feasible. Having a thread per connection will quickly exhaust resources in any loaded system. Having one thread pinging all connections in a loop will produce a terrible performance.
The proper way is to multiplex on the sockets - have a sane number of threads (16, why not), distribute all sockets between those 16 threads and multiplex on those sockets using select() variant - whatever is available in Java for this.

SergeyA
- 61,605
- 5
- 78
- 137