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.
Comments
AlainODea replied ago:
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:
EDIT: for some reason the code block is adding twice as many newlines as there actually are. Sorry about that.
Jakob Jenkov replied ago:
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.
Jakob Jenkov replied ago:
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.
AlainODea replied ago:
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.
Voters For This Link (11)
Voters Against This Link (4)