Link Details

You pick the winners! Login and vote now.
Link 92086 thumbnail
User 131196 avatar

By jj83777
via tutorials.jenkov.com
Published: Jul 02 2008 / 20:23

This is text no. 3 in a series on implementing multithreaded servers in Java. So far the trail discusses a singlethreaded and a simple multithreaded server design. The material covered is still basic, but the trail is growing and soon several more designs will be covered.
  • 11
  • 4
  • 1680
  • 500

Comments

Add your comment
User 237027 avatar

AlainODea replied ago:

0 votes Vote down Vote up Reply

If you write a server this way it allows an unbounded number of threads to be created in response to requests. With enough concurrent requests available memory or threads would be exhausted leading the JVM to throw an OutOfMemoryError.

I would use java.util.concurrent.Executors.newFixedThreadPool(int) to get back an ExecutorService to handle inbound requests as follows:


ExecutorService requestService = Executors.newFixedThreadPool(100);
while(! isStopped()){
Socket clientSocket = null;
try {
clientSocket = this.serverSocket.accept();
} catch (IOException e) {
if(isStopped()) {
System.out.println("Server Stopped.");
return;
}
throw new RuntimeException(
"Error accepting client connection", e);
}

requestService.submit(
new WorkerRunnable(
clientSocket, "Multithreaded Server")
);
}


EDIT: for some reason the code block is adding twice as many newlines as there actually are. Sorry about that.

User 131196 avatar

Jakob Jenkov replied ago:

0 votes Vote down Vote up Reply

That's what I thought too. But read this:

http://paultyma.blogspot.com/2008/03/writing-java-multithreaded-servers.html

It seems creating new threads is cheap, and not as resource intensive as 2-3 years ago. Context switching is cheap too, and so is synchronization.

Anyways, I planned to cover the thread pooled server version too, plus a NIO based server version too. The version you were reading about was only as far I as I got by now.

User 131196 avatar

Jakob Jenkov replied ago:

0 votes Vote down Vote up Reply

If you look closely at my code, you will also notice that I created a WorkerRunnable, not a WorkerThread. That was exactly to make it easier to switch to the thread pooled version.

User 237027 avatar

AlainODea replied ago:

0 votes Vote down Vote up Reply

Very good point. I read through http://paultyma.blogspot.com/2008/03/writing-java-multithreaded-servers.html and it completely changed my understanding of this issue. Threads really are a lot more scalable than they once were in Java.

Thank you for the link! This now has my vote.

Add your comment


Html tags not supported. Reply is editable for 5 minutes. Use [code lang="java|ruby|sql|css|xml"][/code] to post code snippets.