如何在java中实例化动态异步服务工作者

时间:2017-03-20 10:48:02

标签: java dictionary asynchronous static instance

我在银行工作,我使用Java 1.4开发和应用。 我必须异步调用某些AS400服务,所以我决定使用这种方法:我创建一个private static Map并将其填充到static块中。当我必须调用实例时,我获取要作为参数调用的服务的名称,搜索映射是否包含该String作为键并实例化服务类。

我遇到的问题是,在同一个JVM上同时运行许多异步进程,它们会同时检索同一个服务类实例。

例如:

  • 在时间1过程A调用WBX133并在时间10
  • 释放它
  • 在时间3过程B调用WBX220并在时间8发布它
  • 在时间4进程C调用WBX133并在时间13
  • 释放它

由于地图是静态的,我将始终为进程提供与worker类相同的实例,但是,每个进程将具有不同的输入并期望来自同一服务的不同输出。

以下是我解释的代码:

public class AS400ServiceFactory {
   private static Map serviceMap;

   static {
       serviceMap = new HashMap();

       serviceMap.put("WBX133", new Wbx133Service());
       serviceMap.put("WBX134", new Wbx134Service());
       serviceMap.put("WBX220", new Wbx220Service()); 
       serviceMap.put("WBX360", new Wbx360Service());
       serviceMap.put("WBX370", new Wbx370Service());
       serviceMap.put("WBX371", new Wbx371Service());
   }

   public static AS400Container getInstance(String serviceName) {
       ASService service = null;        
       if (serviceMap.containsKey(serviceName)) {
           service = (ASService) serviceMap.get(serviceName);
       }
   }
}

快速(但在我看来,不优雅)的解决方案是,而不是拥有静态地图,只是:

public class AS400ServiceFactory {
   public static AS400Container getInstance(String serviceName) {
      ASService service = null;

      if (("WBX133").equals(serviceName)) {
          service = new Wbx133Service();
      }
      if (("WBX134").equals(serviceName)) {
          service = new Wbx134Service();
      }
      if (("WBX220").equals(serviceName)) {
          service = new Wbx220Service();
      }
      if (("WBX360").equals(serviceName)) {
          service = new Wbx360Service();
      }
      if (("WBX370").equals(serviceName)) {
          service = new Wbx370Service();
      }
      if (("WBX371").equals(serviceName)) {
          service = new Wbx371Service();
      }
   }
}

通过这种方式,我将不再拥有始终拥有相同实例的问题。但是,我将来会有类似60-70服务的东西,并且60-70 if-else if不可读。

任何建议都是相关的。 提前致谢, 弗朗西斯

1 个答案:

答案 0 :(得分:3)

您可以创建服务工厂的地图,然后使用它。

public class AS400ServiceFactory {
  private static Map factories = createFactories();

  private static Map createFactories() {
    Map factories = new HashMap();
    factories.put("WBX133", new ServiceFactory(){ public ASService create() { return new Wbx133Service(); } });
    factories.put("WBX134", new ServiceFactory(){ public ASService create() { return new Wbx134Service(); } });
    factories.put("WBX220", new ServiceFactory(){ public ASService create() { return new Wbx220Service(); } });
    // More factories here
    return factories;
  }

  public static AS400Container getInstance(String serviceName) {
    ServiceFactory factory = (ServiceFactory)factories.get(serviceName);
    ASService service = null;
    if (factory != null) {
      service = factory.create();
    }
    // Rest of the method
  }
  private interface ServiceFactory {
    ASService create();
  }
}