Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restartable Service using Guava

Tags:

java

guava

I'm currently developing an application where I need to manage the state of several services, and stopping/starting them based on some events. The problem is, as stated in the docs, Guava's Service is uni-direccional, meaning, once it's been stopped, it can't be started again.

Since I need to circumvent this problem somehow, I'm faced with a couple of alternatives, which I would like to put out for consideration (especially since there might be drawbacks to each one that I'm not aware of right now).

The first obvious solution to this problem, is to instantiate a new Service when I need to "restart" it. This works, but in my current architecture it would complicate things a bit: currently I'm instatiating all the services, and based on events from an EventBus, starting or stopping them if need be. The class that calls the start and stop methods only saves a reference to a Map of Services, and calls the right method on those instances based on the Event received. If I need to instantiate a new object in response to an Event, I'll have to give up some of the de-coupling I currently have (possibly by keeping the class of each type of Service and invoking the constructor using reflection).

Another possibility is to implement the Service interface as a RestartableThreadedService (or something along these lines). If I took this route, my start() method could create another Thread as if it were the first time, and reset the states.

Is there any clear disadvantage to the second approach? I fear I might be missing some obvious drawback here (besides having to code something a bit more complicated), especially in regards to Thread management.

like image 847
pcalcao Avatar asked Jan 23 '12 18:01

pcalcao


2 Answers

I'd recommend your first approach, but there are better ways to do it than reflection. Using dependency injection, or possibly passing around Supplier<Service> objects instead of using serviceClass.newInstance(), is probably the way to go here.

like image 142
Louis Wasserman Avatar answered Oct 05 '22 19:10

Louis Wasserman


Consider using Guice's scopes.

like image 42
Craig P. Motlin Avatar answered Oct 05 '22 18:10

Craig P. Motlin