Reputation: 383
I have a multi-threading java application. I wonder if this approach is correct. From my main method, I will start two threads. One thread starts listening for an incoming client connection (this is a client-server application). Once a client connects with the server, it starts a new thread to handle the client and this continues for all the client connections. The other thread started by the main program handles the messages received by the clients which are in a common buffer.
My question is: Main thread starts a thread (server) then this thread in-turn starts many threads. Is this correct?
Upvotes: -1
Views: 1577
Reputation: 476
Yes, the main thread can start other threads. There is no problem if the parent thread exits, the child thread will continue running. Please use the main thread to accept new connections and the other threads to handle client requests. Each client thread should maintain its own input/output streams.
Upvotes: 0
Reputation: 439
There is a problem. It is possible to create too many threads on your server concurrently and you are faced with DOS (Denial Of Service).
I propose using java.util.concurrent.ExecutorService implementations.
For example:
Runnable yourRunnable;
ExecutorService executorService = Executors.newFixedThreadPool(50);
executorService.submit(yourRunnable);
Upvotes: 2
Reputation: 2642
You are using somehow wrong approach here ...
The other thread started by the main program handles the messages received by the clients which are in a common buffer.
Why are you using common buffer for all clients? It is NOT thread safe.
Better Approach:
The thread that is handling the client should also handle its own buffer. So create new thread when any client connects and make new buffer for read and write for each client.
Upvotes: 0