java - Session - servlets, in a sevlet i set a static variable to something and this remains the same for all the sessions -


i have simple jsp page hits servlet , in servlet call method class , in method declaring static variable globally , setting value , servlet's task on control jsp page (or page forward request , response to).

so wat happened termed session???

the value set static variable remains same sessions coming next!! why happening. dint earlier session end ?? if has ended, why value static variable have set still remaining in subsequent sessions?? please correct me if wrong. me learn! stackoverflow has never let me down!!!! in advance

static fields in class live until class unloaded , garbage collected. so, static fields in serlvet not live across sessions across whole application, in case, until web application undeployed.

in fact, not wise have field in servlet unless field cannot modified after being initialized or if injected container ejb or cdi bean. because single servlet instance used attend several requests made server, if have non-static field in servlet , update through requests, value can modified 2 or several requests happening @ same time. try keep variables shortest possible scope, example, inside method only.

more info:


from comments, looks real problem design support synchronization across several threads. better option creating object instance shared among threads, use final non-static field handle synchronization:

class myclass {     final object lock = new object();     //other fields in class... }  class multijobs {     class job implements runnable {         myclass myclass;         public job(myclass myclass) {             this.myclass = myclass;         }         @override         public void run() {             //handle job here...             //using synchronization point             synchronize(myclass.lock) {             }         }     }     static final int num_threads = 10;     public void executeseveraljobs() {         executorservice executorservice = executors.newfixedthreadpool(num_threads);         myclass myclass = new myclass();         executorservice.execute(new job(myclass));         executorservice.execute(new job(myclass));         //initialize jobs , add them executorservice         //...         executorservice.shutdown();         //...     } } 

Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

inno setup - TLabel or TNewStaticText - change .Font.Style on Focus like Cursor changes with .Cursor -