I think you should design structure of you service class first. I can suggest following:
public class Service {
private List<Service> dependencies;
// Starts service.
// It should wait until all dependencies started using awaitStart method and then start itself
public void start();
// Blocks current thread until service is started.
// If it is started returns immediately.
public void awaitStart();
// Stops service.
// Awaits until all dependencies are stopped using awaitStop.
public void stop();
// Blocks current thread until service is stopped.
// If it is already stops returns immediately
public void awaitStop();
// Actual code that has service specific code.
// This method may be invoked as last line in 'start' method.
public void run();
}
Next problem is to implement start
and awaitStart
(stop
methods implemented similar). I recommend to use tools from java.util.concurrent
for implementing awaitStart
method. E.g. CountDownLatch. Each service has it's own latch that indicates that server is started. So code for awaitStart
and start
is following:
private CountDownLatch started = new CountDownLatch(1);
public void awaitStart() {
started.await();
}
public void start() {
for (Service service : dependencies) {
service.awaitStart();
}
System.out.println("Service " + name + " is started");
started.countDown();
run();
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…