google 下的AbstractIdleService

来源:互联网 发布:mac大型单机游戏下载 编辑:程序博客网 时间:2024/06/05 09:27

这个提供的service主要是负责一些服务器的启动等。比如一些netty,redis等启动关闭的可以放在里面管理

  • 介绍下AbstractIdleService的使用
    public class Test extends AbstractIdleService{        protected void startUp() throws Exception {            //做一些操作启动的操作。        }        public void shutDown() {            //做一些关闭的操作。        }        main() {            new Test().startAsync().awaitRunning();            new Test().stopAsync().awaitRunning();        }    }
  • 先来介绍下startAsync里面的方法

    流程:
    1. 判断这个是否是new这个状态 (是否有初始化)
    2. 通知监听者启动的状态
    3. 启动
    4. 出现异常
    5. 通知监听者运行

    public final Service startAsync() {      if (monitor.enterIf(isStartable)) {        try {            snapshot = new StateSnapshot(STARTING);            starting();            doStart();        } catch (Throwable startupFailure) {            notifyFailed(startupFailure);        } finally {            monitor.leave();            executeListeners();        }    } else {        throw new IllegalStateException("Service " + this + " has already been started");    }    return this;  }

正在启动的地方
启动和关闭都是各一个线程
就是各种状态转变。。

   private final Service delegate = new AbstractService() {    @Override protected final void doStart() {      executor().execute(new Runnable() {            @Override public void run() {              try {                startUp(); //对外的接口                notifyStarted();              } catch (Throwable t) {                notifyFailed(t);                throw Throwables.propagate(t);              }            }          });    }    @Override protected final void doStop() {      executor().execute(new Runnable() {            @Override public void run() {              try {                shutDown(); //对外接口                notifyStopped();              } catch (Throwable t) {                notifyFailed(t);                throw Throwables.propagate(t);              }            }        });  };   protected Executor executor() {    return new Executor() {      @Override public void execute(Runnable command) {        MoreExecutors.newThread(threadNameSupplier.get(), command).start();      }    };  }
0 0
原创粉丝点击