package com.chenyang.nse.bussiness.tools.thread;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.lang.reflect.Method;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class GenericAsyProcess implements Runnable {
   private static final Logger log = LoggerFactory.getLogger(GenericAsyProcess.class);
   private String methodName;
   private Object service;
   private Object[] args;

   public static void asyCommitThreadPool(String methodName, Object service, Object... args) {
      ThreadFactory namedThreadFactory = (new ThreadFactoryBuilder()).setNameFormat("asyn-pool-%d").build();
      ExecutorService singleThreadPool = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
      singleThreadPool.submit(new GenericAsyProcess(methodName, service, args));
   }

   private GenericAsyProcess(String methodName, Object service, Object... args) {
      this.methodName = methodName;
      this.service = service;
      this.args = args;
   }

   public void run() {
      try {
         Class[] classes = null;
         if (this.args != null) {
            classes = new Class[this.args.length];

            for(int i = 0; i < this.args.length; ++i) {
               classes[i] = this.args[i].getClass();
            }
         }

         Method method = this.service.getClass().getMethod(this.methodName, classes);
         method.invoke(this.service, this.args);
      } catch (Exception e) {
         log.info("异步执行[{}]方法[{}]失败。", this.service.getClass(), this.methodName);
         log.info("参数：{}", this.args, e);
      }

   }
}
