1

I am currently coding a client-server JAVA application and I'm kind of stuck. I searched on the net to find some helpful code. I found this sample (I want to use it when I am waiting for a connection) but I don't really understand what this code is suppose to be doing, could someone out there help out? :)

Executor threadpool = Executors.newScheduledThreadPool(maxClients);
Harry
  • 3,031
  • 7
  • 42
  • 67
sandKa
  • 11
  • 1
  • To wait client requests to open a connection, you need one thread which in a loop calls to serversockect.accept(). You need not threadpool. To wait message from the client after connection is opened, you can use thread pool, but it is more complex than using a separate thread per client, and when maxClients is surpassed, extra client connections would be accepted but not handled. So don't use thread pool in the prototype version of your server. – Alexei Kaigorodov Nov 12 '14 at 19:18
  • your answer is here http://stackoverflow.com/questions/12588476/multithreading-socket-communication-client-server – Andrés Oviedo Nov 12 '14 at 21:24

1 Answers1

0

The Executor interface and the Executors Factory help you use ThreadPools.

In your case: You want to handle incoming client connection concurrently. So you need a Thread for each. So submitting a Task to an Executor is a convenient way to not be bothered with Thread creation etc.

So the line

Executor threadpool = Executors.newScheduledThreadPool(maxClients);

declares threadpool to be an Executor ( that Tasks can be submitted to later on ) but you don't care which of the implementations. The right side of the "=" then uses the Factory to retrieve an instance of one of the implementations of Executor. In this case it is a ScheduledThreadPool with at least maxClients Threads waiting for new Tasks.

In the code it will probably used like

threadpool.execute( new ClientHandler(socket) );

where ClientHandler is some helperclass implementing Runnable, that handles IO with the Client.

Fildor
  • 14,510
  • 4
  • 35
  • 67