java - Servlet issue when high concurrency happens -
this sister question related previous post here: simple web server when high-concurrency met
the interview question is:
public class counterservlet extends httpservlet{ private volatile static int counter=0; public int getcounter() { return counter; } public void service(httpservletrequest request httpservletresponse response) throws ioexception { counter++; printwriter out=response.getwriter(); out.write("hello"); } what issue there in code above when high concurrency encountered? analysis is:servlet singleton, there issues in synchronization.it has declared counter volatile, not prevent issue.i suggest synchronize service method?
if access static values through multiple thread each thread can have it's local cached copy! avoid can declare variable static volatile , force thread read each time global value. however, volatile not substitute proper synchronisation!
you need synchronize code, although doing increment on counter not mean entire method atomic. there may multiple threads incrementing @ same time using current value registers. may lead undesirable result.
you need either synchronize method or use atomicinteger such trivial operation.
Comments
Post a Comment