java - Is this caching a closure thread save? -


public class exampleservlet extends httpservlet{      private closure closure;      @override     protected void dopost(final httpservletrequest req, httpservletresponse resp) throws servletexception, ioexception {         // stuff here...         if (this.closure == null){             this.closure = new closure(){                 @override                 public void somefunction(){                     req.getrequesturi(); // it...                 }             }         }          // later...         this.closure.somefunction(); // << thread-save??          // more stuff here...     } } 

in example, have no control on closure!

if test this, works fine. question is:

does every request-thread new copy of closure-field? otherwise, when new request comes in, referenced req-field change while somefunction() still executing. or handled declaring req final?

the same servlet instance used requests.

so closure created first request , shared among subsequent requests.

it continue refer initial request hit servlet, this should not work @ all, without multiple threads (single-threaded sequential requests broken).

if have multiple threads complications, such having synchronize on servlet instance "lazy singleton initialization" part. ideally, such initialization done in servlet's init method instead.

cannot make local variable inside of dopost?

does every request-thread new copy of closure-field?

no. share same servlet, (single) closure field.

when new request comes in, referenced req-field change while somefunction() still executing.

no. captured req not change lifetime of closure. final , copied servlet when closure first created. continue refer first request hit servlet.

or handled declaring req final?

that technical requirement due nature of how closures in java implemented. don't capture variables, capture snapshot values of variables copy.


Comments

Popular posts from this blog

python - mat is not a numerical tuple : openCV error -

c# - MSAA finds controls UI Automation doesn't -

wordpress - .htaccess: RewriteRule: bad flag delimiters -