java - Wait for static initializer -


i want have static field in class automatically initialized when class loaded.

something this:

class servicebase {     static object lock = new object();     static servicebase service;     static void setservice(servicebase service) {         synchronized (lock) {             servicebase.service = service;             lock.notifyall();         }     }     void f() throws exception {         synchronized (lock) {             while (service == null){                 lock.wait();                         }        }        //use service    } }  class serviceimpl extends servicebase {     static {         servicebase.setservice(ne serviceimpl());     } }  

the problem is f called before serviceimpl loaded, hangs in deadlock.

what's best way of initializing service instance? (i cannot use spring or other huge frameworks)

your approach overly complex. should not need worry synchronization or of that.

the obvious simplification pass service instance constructor parameter servicebase:

class servicebase {   private final service service;    servicebase(service service) {     this.service = checknotnull(service);   }    void f() {     // service guaranteed present.   } } 

this way, can never call f() before non-null service available.

if concern want same instance of serviceimpl used every time, create servicebaseprovider class use instances of servicebase, instead of constructing them directly:

class servicebaseprovider {   private static serviceimpl instance = new serviceimpl();    static servicebase getinstance() {     return new servicebase(instance);   } } 

or, of course, inject same instance of servicebase wherever required, makes easier (for example) inject mock instance during tests.


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -