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
Post a Comment