Tuesday 15 January 2013

multithreading - Best approach for ServerSocket Java -



multithreading - Best approach for ServerSocket Java -

i have serversocket in 1 of classes of java project. socket receives commands led new actions. example:

deleteallfromdb--> deletes entries on db.

sendmsgtox--> creates new message sent x.

something like:

in = new scanner(s.getinputstream()); message = in.next(); if (message.equalsignorecase("deleteallfromdb"){ //code //more code //even more code } ...

ok, think got thought (it's quite simple utilize examples because english language skills may confuse audience).

the problem methods within class getting bigger , heavier, socket doesn't read incoming messages until method executed , finished.

i think have 2 approaches solve this:

1. multithreaded server

rather processing incoming requests in same thread accepts client connection, connection handed off worker thread processes request

http://tutorials.jenkov.com/java-multithreaded-servers/multithreaded-server.html

2. threaded methods

once read incoming request (message=in.next()), launch thread responsible of methods executed (deletefromdb, sendmsgtox,etc).

any advice appreciated. also, mention, i'm working osgi framework, thou don't think that's relevant question (just in case..).

thanks in advance!

you execute code handles message in executorservice.

like that:

//outside handler: pool = executors.newfixedthreadpool(poolsize); // on message receipt message = in.next(); pool.execute(new messagehandler(message));

so can nicely scale setting poolsize.

so guess method 2

java multithreading sockets osgi serversocket

No comments:

Post a Comment