0

I have multi-threading java application. I am wondering if this approach is correct. From my main method I will start two threads. One thread start listening for in coming client connections (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), this thread in-turn starts many threads. Is this correct?

Raedwald
  • 46,613
  • 43
  • 151
  • 237
user340
  • 375
  • 12
  • 28
  • Please always include relevant parts of your own code. – meskobalazs Jan 26 '15 at 09:59
  • Starting one thread for every new connection works for a small number of connections, but scales badly. I suggest you try to use a ThreadPool for handling open connections, which can be much more efficient. – Jan Henke Jan 26 '15 at 11:34
  • possible duplicate of [One thread per client. Doable?](http://stackoverflow.com/questions/3867042/one-thread-per-client-doable) – Raedwald Jan 26 '15 at 12:30

3 Answers3

1

There is a problem. It is possible to create many threads on your server concurrently and you face 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);
0

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.

Junaid
  • 2,572
  • 6
  • 41
  • 77
0

Yes main thread can start other threads. There is no problem if parent thread exits, the child thread will run. Please use main thread to accept new connections and other thread to handle client request and then handle client thread should maintains there own input output stream.

Pranav Agrawal
  • 466
  • 6
  • 17