Sunday, 15 June 2014

java - Starting thread in a servlet, what can be the issues? -



java - Starting thread in a servlet, what can be the issues? -

i have web application, that, on single request may require load hundreds of data. problem info scattered. so, have load info several places, apply filters on them, process them , respond. performing these operations sequentially makes servlet slow!

so have thought of loading info in separate threads t[i] = new thread(loaddata).start();, waiting threads finish using while(i < count) t[i].join(); , when done, bring together info , respond.

now not sure if approach right or there improve method. have read somewhere spawning thread in servlets not advisable.

my desired code this.

protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { iterable<?> requireddata = requireddata(request); thread[] t = new thread[requireddata.size]; int = 0; while (requireddata.hasnext()) { t[i] = new thread(new loaddata(requiredata.next())).start(); i++; } for(i = 0 ; < t.length ; i++) t[i].join(); // after getting info process , respond! }

the main problem you'll bring server knees if many concurrent requests comes in servlet, because don't limit number of threads can spawned. problem maintain creating new threads instead of reusing them, inefficient.

these 2 problems solved using thread pool. , java has native back upwards them. read the tutorial.

also, create sure shutdown thread pool when webapp shut down, using servletcontextlistener.

java multithreading tomcat servlets asynchronous

No comments:

Post a Comment