静态ThreadPool与Singleton ThreadPool

时间:2015-12-02 11:03:56

标签: java static singleton threadpoolexecutor non-static

在下面的类中我使用SingleThreadPool(它是静态的)并且我确保静态线程池只使用一个布尔对象初始化一次并使其同步(参见init()我已经将ThreadPoolExecutor设置为静态,因为我想在多个传入请求中重用同一个池。

这个类有一个内部类,即Validator,它实现了callable并返回一个布尔值。

重写的submit方法,迭代每个输入并将Validator(Task)提交给ThreadPoolExecutor。

public class ValidationProcessor implements IValidation {
 //should this be static or singleton
 private static ThreadPoolExecutor executor;    
 private volatile static Boolean initialized= new Boolean(Boolean.FALSE);
 List<Input> inputList;

 public ValidationProcessor(List<Input> inputList) {
      init();
      this.inputList=inputList;
 }

  public static void init() {
        try {
            synchronized (initialized) {
                if (!initialized.booleanValue()) {
                    LOG.debug("Initializing..................thread pool...");
                    final BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(1000);
                    executor = new ThreadPoolExecutor(3, 5, 60, TimeUnit.SECONDS,
                                                      queue);
                    initialized=new Boolean(Boolean.TRUE);
                }
            }
        } catch (Exception e) {
            LOG.error("Exception while initialising the thread pool {} and stack trace {}" , ExceptionUtils.getFullStackTrace(e));
        }
    } 

      public class Validator implements Callable<Boolean> {

            private final Logger LOG = LoggerFactory.getLogger(Validator.class.getName());
            Input input;

            public ValidateNPublishTask(Input input) {
                this.input=input;
            }

            public boolean validate() {
                final Timer validateTimer = new Timer();
                final boolean isValid = Validator.validate(input);//some process
                return isValid;
            }

            @Override
            public Boolean call() throws Exception {
                return validate();
            }

        }

    @Override
        public boolean submit() {
            Boolean consolidatedOutput=new Boolean(Boolean.TRUE);
            List<Future<Boolean>> validationResult = new ArrayList<Future<Boolean>>();
            try {
                for (final Input i : inputs) {  
                    Validator validate = new Validator(input);
                    Future<Boolean> r = getExecutor().submit(validate);
                    validationResult.add(r);
                }
                for (Future<Boolean> fr : validationResult) {
                    if (!fr.get()) {
                       //change consolidatedOutput to false;
                        break; // at-least one failure, return status as failure
                    }
                }
            } catch (InterruptedException | ExecutionException e) {
                LOG.error("Exception while validating the input {} exception {}",  ExceptionUtils.getFullStackTrace(e)});
            }
            return consolidatedOutput;
        }

public static ThreadPoolExecutor getExecutor() {
    return executor;
}
}

从另一个类Processor.java调用上面的类,如下所示。此处理器在Web-Application中调用。因为,ValidationProcessor是局部变量,它是线程安全的。

 Public Class Processor {

    public Response process(Input input) {
           List<Input> inputList = load();
           IValidation validateNPublishObj = new ValidationProcessor(inputList);
           emailResponse=validateNPublishObj.submit();
    }

    public List<Input> load() {
          //return list of inputs <Input>
    }

    }

为简单起见,我已将某些实现留空,如load()。

我的问题更多来自设计角度。

  1. 在我的ValidationProcessor类中,ThreadPoolExecutor应该是静态的还是单例的。
  2. / *示例单例* /

     public class MyThreadPoolExecutor {
            private final ThreadPoolExecutor executor;
            private static MyThreadPoolExecutor threadPoolInstance = null;
    
            private MyThreadPoolExecutor() {
              executor = new ThreadPoolExecutor(...); 
            }
    
        static {
            threadPoolInstance = new MyThreadPoolExecutor();
        }
    
        public static MyThreadPoolExecutor getInstance() {
            return threadPoolInstance;
        }
    
    }
    
    1. 如果单例的实例变量而不是静态(在上面的例子中),它是否有任何区别。我的重点是使用单线程池,我不想为每个传入的请求使用/创建一个新的ThreadPool。
    2. 基本上我希望我的所有线程都使用相同的ThreadPoolExecutor,而不是每当创建ValidationProcessor实例时都创建一个ThreadPoolExecutor实例。

      P.S:无需验证提交内部的逻辑,假设它编译并正常工作。 此外,ThreadPoolExecutor不在应用程序之间共享,目前仅在此类中使用。

0 个答案:

没有答案