I have a ServerSocket
in one of the classes of a Java project. This socket receives some commands that led to new actions. For example:
deleteAllFromDB
--> Deletes all the entries on the DB.
sendMsgToX
--> Creates a new message that is sent to X.
Something like:
in = new Scanner(s.getInputStream());
message = in.next();
if (message.equalsIgnoreCase("deleteAllFromDB"){
//code
//more code
//even more code
}
...
Ok, I think you got the idea (it's quite simple but I use examples because my english skills may confuse the audience).
The problem is that the methods inside the class are getting bigger and heavier, so the socket doesn't read incoming messages until the method is executed and finished.
I think I have 2 approaches to solve this:
1. Multithreaded Server
Rather than processing the incoming requests in the same thread that accepts the client connection, the connection is handed off to a worker thread that processes the request
http://tutorials.jenkov.com/java-multithreaded-servers/multithreaded-server.html
2. Threaded methods
Once I read the incoming request (message=in.next()
), I launch a thread that is responsible of the methods to be executed (deleteFromDB, sendMsgToX
,etc).
Any advice would be really appreciated. Also, just to mention, I'm working with the OSGi framework, even thou I don't think that's relevant for the question (just in case..).
Thanks in advance!
You could simply execute the code that handles the message in an ExecutorService.
Like that:
//Outside the handler:
pool = Executors.newFixedThreadPool(poolSize);
// On message receipt
message = in.next();
pool.execute(new MessageHandler(message));
So you can nicely scale by setting the poolSize.
So I guess that would be method 2