Example usage for com.google.common.util.concurrent AbstractExecutionThreadService AbstractExecutionThreadService

List of usage examples for com.google.common.util.concurrent AbstractExecutionThreadService AbstractExecutionThreadService

Introduction

In this page you can find the example usage for com.google.common.util.concurrent AbstractExecutionThreadService AbstractExecutionThreadService.

Prototype

protected AbstractExecutionThreadService() 

Source Link

Document

Constructor for use by subclasses.

Usage

From source file:com.github.kroepke.Main.java

public static void main(String[] args) {

    final LinkedBlockingQueue<Long> queue = new LinkedBlockingQueue<>(100);

    Processor processor = new Processor();

    AbstractExecutionThreadService consumer = new Consumer(1, processor, queue);
    AbstractExecutionThreadService consumer1 = new Consumer(2, processor, queue);
    AbstractExecutionThreadService consumer2 = new Consumer(3, processor, queue);

    AbstractExecutionThreadService producer = new Producer(queue);
    AbstractExecutionThreadService waterMarkPrinter = new AbstractExecutionThreadService() {
        @Override// ww w  . jav  a2  s .c o m
        protected void run() throws Exception {
            while (isRunning()) {
                sleepUninterruptibly(1, SECONDS);
                log.info("Queue watermark {}, producer blocks {}", queue.size(), producerBlocks.get());
            }
        }
    };

    waterMarkPrinter.startAsync().awaitRunning();
    consumer.startAsync().awaitRunning();
    consumer1.startAsync().awaitRunning();
    consumer2.startAsync().awaitRunning();
    producer.startAsync().awaitRunning();

    sleepUninterruptibly(1, MINUTES);

    producer.stopAsync().awaitTerminated();
    consumer.stopAsync().awaitTerminated();
    consumer1.stopAsync().awaitTerminated();
    consumer2.stopAsync().awaitTerminated();
    waterMarkPrinter.stopAsync().awaitTerminated();

}

From source file:com.technostar98.tcbot.bot.BotManager.java

public static void start() {
    synchronized (lock) {
        List<Service> services = Lists.newLinkedList();
        for (final Map.Entry<String, IRCBot> e : bots.entrySet()) {
            Service s = new AbstractExecutionThreadService() {
                IRCBot bot = e.getValue();
                String server = e.getKey();

                @Override//  w ww.j  av  a2 s  .c  o  m
                protected void run() throws Exception {
                    Logger.info("Bot for %s server starting up.", server);
                    bot.getBot().startBot();
                }

                @Override
                protected void startUp() throws Exception {
                    super.startUp();
                }

                @Override
                protected void shutDown() throws Exception {
                    super.shutDown();
                    /*System.out.println("Shutting down.");
                    bot.getBot().stopBotReconnect();
                    bot.getBot().sendIRC().quitServer("Adios");
                    getBotOutputPipe(server).messengerPipeline.setOutputEnabled(false);
                    getBotOutputPipe(server).closeListener();
                    try {
                    Thread.sleep(50L);
                    } catch (InterruptedException e1) {
                    e1.printStackTrace();
                    }
                    bot.getBot().getInputParser().close();
                    bots.remove(server);*/
                }

                @Override
                protected void triggerShutdown() {
                    super.triggerShutdown();
                    Logger.info("Bot for server %s is shutting down. Closing all tied resources.", server);

                    try {
                        shutDown();
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }
                }
            };
            services.add(s);
        }

        manager = new ServiceManager(services);
        manager.addListener(new ServiceManager.Listener() {
            @Override
            public void healthy() {
                super.healthy();
                Logger.info("All bot instances started correctly.");
            }

            @Override
            public void stopped() {
                super.stopped();
                Logger.info("All bots shutdown.");
            }

            @Override
            public void failure(Service service) {
                super.failure(service);
                try {
                    IRCBot bot = (IRCBot) service.getClass().getDeclaredField("bot").get(service);
                    Logger.info("Bot for server %s has failed to start.",
                            bot.getServerConfiguration().getServerName());
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        });
        manager.startAsync();

        dataManager = new Thread(() -> {
            while (bots.size() > 0) {
                try {
                    Thread.sleep(600000);
                } catch (InterruptedException e) {
                    //ignore
                }

                bots.keySet().forEach(
                        s -> getBotOutputPipe(s).getChannelManagers().forEach(c -> c.saveChannelData()));
            }
        });
        dataManager.start();
    }
}

From source file:org.graylog2.plugin.inputs.transports.GeneratorTransport.java

@Override
public void doLaunch(final MessageInput input) throws MisfireException {
    generatorService = new AbstractExecutionThreadService() {
        @Override/*  ww w .  j a  v a2  s .  c  o m*/
        protected void run() throws Exception {
            while (isRunning()) {

                if (isThrottled()) {
                    blockUntilUnthrottled();
                }
                final RawMessage rawMessage = GeneratorTransport.this.produceRawMessage(input);
                if (rawMessage != null) {
                    input.processRawMessage(rawMessage);
                }
            }
        }
    };

    generatorService.startAsync();
}

From source file:com.griddynamics.jagger.monitoring.MonitoringTaskDistributor.java

@Override
protected Service performDistribution(final ExecutorService executor, final String sessionId,
        final String taskId, final MonitoringTask task, final Map<NodeId, RemoteExecutor> remotes,
        final Multimap<NodeType, NodeId> availableNodes, final Coordinator coordinator) {

    return new AbstractExecutionThreadService() {
        @Override/* w  w  w.  ja  v a 2s. c  o  m*/
        protected void run() throws Exception {
            MonitoringController monitoringController = null;
            try {
                MonitoringTerminationStrategy terminationStrategy = task.getTerminationStrategy().get();

                monitoringController = new MonitoringController(sessionId, taskId, availableNodes, coordinator,
                        remotes.keySet(), ttl);
                monitoringController.startMonitoring();

                while (true) {
                    if (!isRunning()) {
                        log.debug("Going to terminate work. Requested from outside");
                        break;
                    }

                    Map<NodeId, MonitoringStatus> status = monitoringController.getStatus();

                    if (terminationStrategy.isTerminationRequired(status)) {
                        log.debug("Going to terminate work. According to termination strategy");
                        break;
                    }

                    // todo mairbek: configure
                    TimeUtils.sleepMillis(500);
                }

                taskExecutionStatusProvider.setStatus(taskId, TaskData.ExecutionStatus.SUCCEEDED);
            } catch (Exception e) {
                taskExecutionStatusProvider.setStatus(taskId, TaskData.ExecutionStatus.FAILED);
                log.error("Monitoring task error: ", e);
            } finally {
                if (monitoringController != null) {
                    log.debug("Going to stop monitoring");
                    monitoringController.stopMonitoring();
                    log.debug("Monitoring stopped");
                }
            }
        }

        @Override
        public String toString() {
            return MonitoringTask.class.getName() + " distributor";
        }

    };
}

From source file:ec.nbdemetra.ui.demo.FakeTsProvider.java

public FakeTsProvider() {
    super(LoggerFactory.getLogger(FakeTsProvider.class), "Fake", TsAsyncMode.Once);

    dataBuilder = new DemoUtils.RandomTsCollectionBuilder();
    normalData = dataBuilder.build();//from w w  w .  j  av a  2 s.c om

    DataSource.Builder builder = DataSource.builder(providerName, "");
    for (DataType o : DataType.values()) {
        dataTypeParam.set(builder, o);
        support.open(builder.build());
    }

    dataTypeParam.set(builder, DataType.UPDATING);
    final TsMoniker updatingMoniker = toMoniker(builder.build());

    this.service = new AbstractExecutionThreadService() {

        @Override
        protected Executor executor() {
            return Executors.newSingleThreadExecutor(
                    new ThreadFactoryBuilder().setDaemon(true).setPriority(Thread.MIN_PRIORITY).build());
        }

        @Override
        protected void run() throws Exception {
            while (isRunning()) {
                queryTsCollection(updatingMoniker, TsInformationType.All);
                TimeUnit.SECONDS.sleep(3);
            }
        }
    }.startAsync();
}