Tuesday, June 17, 2008

jSuneido - Server (again)

First I thought the socket server portion of Suneido would be easy in Java. Then I realized it wasn't going to be as easy as I thought. Now, after reading Java Concurrency in Practice (recommended), I'm back to thinking it'll be "easy" (relatively).

I won't need to use Grizzly or MINA or any other library/framework. The key is the Executor system which was introduced in Java 5. I can use the Executors.newCachedThreadPool to process requests.

This will result in (pooled) thread-per-request which is what I want. So if there are 50 users connected, but only 4 requests active at a given time, there will only be 4 worker threads. Actually, it's a bit more complicated because inactive threads are kept around for a while (cached) in case they're needed.

CachedThreadPool uses an unbounded number of threads. This isn't so good for uncontrolled situations because it can lead to problems like denial of service attacks. But for the situations where Suneido applications are used - on local area networks - it should be a reasonable choice.

It doesn't use the Leader/Followers pattern but it does use a SynchronousQueue to pass requests from the "dispatcher" to the worker threads. This passes the requests "directly" from one thread to another, avoiding the overhead of adding and removing requests to a normal queue.

I find this flip-flopping between optimism and pessimism quite common, both on small scales and on larger scales. Learning often fits into one of two categories - learning how to do things, or learning that things are more complex than you thought.

No comments: