All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.cedarsoft.gdao.async.AsynchronousServiceManager Maven / Gradle / Ivy

The newest version!
package com.cedarsoft.gdao.async;

import com.cedarsoft.async.AsyncCallSupport;
import com.cedarsoft.async.CallbackCaller;
import com.cedarsoft.gdao.GenericService;
import com.cedarsoft.gdao.GenericServiceManager;
import com.cedarsoft.utils.Cache;
import com.cedarsoft.utils.HashedCache;
import org.jetbrains.annotations.NotNull;

import java.util.Iterator;

/**
 *
 */
public class AsynchronousServiceManager implements GenericServiceManager {
  @NotNull
  private final AsyncCallSupport> asyncCallSupport = new AsyncCallSupport>();

  @SuppressWarnings( {"MismatchedQueryAndUpdateOfCollection"} )
  @NotNull
  private final Cache, AsynchronousService> serviceCache = new HashedCache, AsynchronousService>(
          new Cache.Factory, AsynchronousService>() {
            @NotNull
            public AsynchronousService create( @NotNull Class key ) {
              return asyncCallSupport.invoke( new AsyncServiceCreator( key ) );
            }
          }
  );

  public AsynchronousServiceManager( @NotNull final String description, @NotNull final GenericServiceManager delegatingManager ) {
    asyncCallSupport.initializeWorker( new CallbackCaller>() {
      @NotNull
      public String getDescription() {
        return description;
      }

      public Object call( @NotNull AsyncServiceCreator callback ) throws Exception {
        return callback.execute( delegatingManager );
      }
    } );
  }

  @NotNull
  public  GenericService getService( @NotNull Class type ) {
    return ( GenericService ) serviceCache.get( type );
  }

  public void shutdown() {
    for ( Iterator> it = serviceCache.values().iterator(); it.hasNext(); ) {
      AsynchronousService service = it.next();
      service.shutdown();
      it.remove();
    }
    asyncCallSupport.shutdown();
  }

  private static class AsyncServiceCreator {
    @NotNull
    private final Class key;

    private AsyncServiceCreator( @NotNull Class key ) {
      this.key = key;
    }

    @NotNull
    public AsynchronousService execute( @NotNull GenericServiceManager delegatingManager ) {
      GenericService service = delegatingManager.getService( key );
      AsynchronousService asynchronousService = new AsynchronousService();
      asynchronousService.initializeDelegatingService( service );
      return asynchronousService;
    }
  }
}