Search code examples
mysqlsessionshutdowndropwizardbroken-pipe

Correct way to kill a session in a distributed system


I am working on a distributed java projct that uses the AKKA framework and runs on a dropwizard server. I create a session at application startup and use this session throughout all of my actors in the following way

MyApplication.java

    public void run() {
      final Session actorSession = hibernate.getSessionFactory()
            .openSession();
     // pass this session to various actors
      final ActorSystem system = ActorSystem.create("myActorSystem");
      environment.lifecycle().manage(new ActorSystemGuardian(system));

      system.registerOnTermination(new Runnable() {
            public void run() {
            //Clean all resources after actor termination
            actorSession.close();
        }

ActorSystemGuardan.java

  public class ActorSystemGuardian implements Managed {
    private ActorSystem system;
    public ActorSystemManager(ActorSystem system) {
      this.system = system;
    }

    public void start() throws Exception {

    }

    public void stop() throws Exception {
      system.shutdown();

   }

}

Does this ensure the proper cleaning of all resources? Will the actorSession be closed ? All the actors need to be using the same session throught the lifecyclye of the application. Is there a way to make this session persistent?


Solution

  • I fixed the problem by passing the sessionFactory instead of a session in the following way

    final SessionFactory actorSessionFactory = hibernate.getSessionFactory()
    

    This factory can then be used to spawn ephemeral sessions which can be(should be) closed after use.

    system.registerOnTermination(new Runnable() {
            public void run() {
            //Clean all resources after actor termination
    
        }
    

    The system.registerOnTermination(new Runnable) is called only when the actor system is shut down and should not be tied with sessions.