Non-Secure:
@NotThreadSafepublic class Unsafecountingfactorizer extends Genericservlet implements Servlet { private Long Count = 0; Public long GetCount () { return count; } public void Service (ServletRequest req, Servletresponse resp) { BigInteger i = extractfromrequest (req); biginteger[] factors = factor (i); ++count; Encodeintoresponse (resp, factors); } void Encodeintoresponse (Servletresponse res, biginteger[] factors) { } BigInteger extractfromrequest ( ServletRequest req) { return new BigInteger ("7"); } Biginteger[] Factor (BigInteger i) { //doesn ' t really factor return new biginteger[] {i}; }}
Safety:
@ThreadSafepublic class Countingfactorizer extends Genericservlet implements Servlet { private final Atomiclong Count = new Atomiclong (0); Public long GetCount () {return count.get ();} public void Service (ServletRequest req, Servletresponse resp) { BigInteger i = extractfromrequest (req); biginteger[] factors = factor (i); Count.incrementandget (); Encodeintoresponse (resp, factors); } void Encodeintoresponse (Servletresponse res, biginteger[] factors) {} BigInteger extractfromrequest ( ServletRequest req) {return null;} Biginteger[] Factor (BigInteger i) {return null;}}
Java concurrent Programming-thread safety 1:servlet access statistics