Example usage for java.util.concurrent Executors newSingleThreadScheduledExecutor

List of usage examples for java.util.concurrent Executors newSingleThreadScheduledExecutor

Introduction

In this page you can find the example usage for java.util.concurrent Executors newSingleThreadScheduledExecutor.

Prototype

public static ScheduledExecutorService newSingleThreadScheduledExecutor(ThreadFactory threadFactory) 

Source Link

Document

Creates a single-threaded executor that can schedule commands to run after a given delay, or to execute periodically.

Usage

From source file:com.adaptris.core.interceptor.SlowMessageNotification.java

@Override
public void start() throws CoreException {
    executor = Executors.newSingleThreadScheduledExecutor(new ManagedThreadFactory(getClass().getSimpleName()));
    scheduleTask();/*from  w w w. j av  a 2s .c o m*/
}

From source file:com.couchbase.lite.Manager.java

/**
 * Constructor/* w  ww  .  ja va  2s .  co  m*/
 *
 * @throws java.lang.SecurityException - Runtime exception that can be thrown by File.mkdirs()
 */
@InterfaceAudience.Public
public Manager(Context context, ManagerOptions options) throws IOException {

    Log.d(Database.TAG, "Starting Manager version: %s", Manager.VERSION);

    this.context = context;
    this.directoryFile = context.getFilesDir();
    this.options = (options != null) ? options : DEFAULT_OPTIONS;
    this.databases = new HashMap<String, Database>();
    this.encryptionKeys = new HashMap<String, Object>();
    this.replications = new ArrayList<Replication>();

    if (!directoryFile.exists()) {
        directoryFile.mkdirs();
    }
    if (!directoryFile.isDirectory()) {
        throw new IOException(
                String.format(Locale.ENGLISH, "Unable to create directory for: %s", directoryFile));
    }

    upgradeOldDatabaseFiles(directoryFile);

    // this must be a single threaded executor due to contract w/ Replication object
    // which must run on either:
    // - a shared single threaded executor
    // - its own single threaded executor
    workExecutor = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "CBLManagerWorkExecutor");
        }
    });
}

From source file:com.codefollower.lealone.omid.tso.TSOHandler.java

/**
 * Constructor/*from ww  w. j  a v  a2s .  c om*/
 * @param channelGroup
 */
public TSOHandler(ChannelGroup channelGroup, TSOState state, int batchSize) {
    this.channelGroup = channelGroup;
    this.timestampOracle = state.getTimestampOracle();
    this.sharedState = state;

    this.flushThread = new FlushThread();
    this.scheduledExecutor = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(Thread.currentThread().getThreadGroup(), r);
            t.setDaemon(true);
            t.setName("Flush Thread");
            return t;
        }
    });
    this.batchSize = batchSize;
}

From source file:com.yahoo.omid.tsoclient.TSOClientImpl.java

TSOClientImpl(Configuration conf, MetricRegistry metrics) {

    this.metrics = metrics;

    // Start client with Nb of active threads = 3 as maximum.
    int tsoExecutorThreads = conf.getInt(TSO_EXECUTOR_THREAD_NUM_CONFKEY, DEFAULT_TSO_EXECUTOR_THREAD_NUM);

    factory = new NioClientSocketChannelFactory(
            Executors/*w ww . j a  va2 s.  co m*/
                    .newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("tsoclient-boss-%d").build()),
            Executors.newCachedThreadPool(
                    new ThreadFactoryBuilder().setNameFormat("tsoclient-worker-%d").build()),
            tsoExecutorThreads);
    // Create the bootstrap
    bootstrap = new ClientBootstrap(factory);

    requestTimeoutMs = conf.getInt(REQUEST_TIMEOUT_IN_MS_CONFKEY, DEFAULT_REQUEST_TIMEOUT_MS);
    requestMaxRetries = conf.getInt(REQUEST_MAX_RETRIES_CONFKEY, DEFAULT_TSO_MAX_REQUEST_RETRIES);
    retryDelayMs = conf.getInt(TSO_RETRY_DELAY_MS_CONFKEY, DEFAULT_TSO_RETRY_DELAY_MS);

    LOG.info("Connecting to TSO...");
    // Try to connect to TSO from ZK. If fails, go through host:port config
    try {
        connectToZK(conf);
        configureCurrentTSOServerZNodeCache();
        HostAndPort hp = getCurrentTSOHostAndPortFoundInZK();
        LOG.info("\t* Current TSO host:port found in ZK: {}", hp);
        setTSOAddress(hp.getHostText(), hp.getPort());
    } catch (ZKException e) {
        LOG.warn("A problem connecting to TSO was found ({}). Trying to connect directly with host:port",
                e.getMessage());
        String host = conf.getString(TSO_HOST_CONFKEY);
        int port = conf.getInt(TSO_PORT_CONFKEY, DEFAULT_TSO_PORT);
        if (host == null) {
            throw new IllegalArgumentException("tso.host missing from configuration");
        }
        setTSOAddress(host, port);
    }

    fsmExecutor = Executors
            .newSingleThreadScheduledExecutor(new ThreadFactoryBuilder().setNameFormat("tsofsm-%d").build());
    fsm = new FsmImpl(fsmExecutor);
    fsm.setInitState(new DisconnectedState(fsm));

    ChannelPipeline pipeline = bootstrap.getPipeline();
    pipeline.addLast("lengthbaseddecoder", new LengthFieldBasedFrameDecoder(8 * 1024, 0, 4, 0, 4));
    pipeline.addLast("lengthprepender", new LengthFieldPrepender(4));
    pipeline.addLast("protobufdecoder", new ProtobufDecoder(TSOProto.Response.getDefaultInstance()));
    pipeline.addLast("protobufencoder", new ProtobufEncoder());
    pipeline.addLast("handler", new Handler(fsm));

    bootstrap.setOption("tcpNoDelay", true);
    bootstrap.setOption("keepAlive", true);
    bootstrap.setOption("reuseAddress", true);
    bootstrap.setOption("connectTimeoutMillis", 100);
}

From source file:org.apache.bookkeeper.replication.Auditor.java

public Auditor(final String bookieIdentifier, ServerConfiguration conf, ZooKeeper zkc, StatsLogger statsLogger)
        throws UnavailableException {
    this.conf = conf;
    this.bookieIdentifier = bookieIdentifier;
    this.statsLogger = statsLogger;

    numUnderReplicatedLedger = this.statsLogger.getOpStatsLogger(ReplicationStats.NUM_UNDER_REPLICATED_LEDGERS);
    uRLPublishTimeForLostBookies = this.statsLogger
            .getOpStatsLogger(ReplicationStats.URL_PUBLISH_TIME_FOR_LOST_BOOKIE);
    bookieToLedgersMapCreationTime = this.statsLogger
            .getOpStatsLogger(ReplicationStats.BOOKIE_TO_LEDGERS_MAP_CREATION_TIME);
    checkAllLedgersTime = this.statsLogger.getOpStatsLogger(ReplicationStats.CHECK_ALL_LEDGERS_TIME);
    numLedgersChecked = this.statsLogger.getCounter(ReplicationStats.NUM_LEDGERS_CHECKED);
    numFragmentsPerLedger = statsLogger.getOpStatsLogger(ReplicationStats.NUM_FRAGMENTS_PER_LEDGER);
    numBookiesPerLedger = statsLogger.getOpStatsLogger(ReplicationStats.NUM_BOOKIES_PER_LEDGER);
    numBookieAuditsDelayed = this.statsLogger.getCounter(ReplicationStats.NUM_BOOKIE_AUDITS_DELAYED);
    numDelayedBookieAuditsCancelled = this.statsLogger
            .getCounter(ReplicationStats.NUM_DELAYED_BOOKIE_AUDITS_DELAYES_CANCELLED);

    initialize(conf, zkc);/*www . java  2  s  . c  o  m*/

    executor = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r, "AuditorBookie-" + bookieIdentifier);
            t.setDaemon(true);
            return t;
        }
    });
}

From source file:com.taobao.gecko.service.impl.BaseRemotingController.java

public final synchronized void start() throws NotifyRemotingException {
    if (this.started) {
        return;//from w  w  w .  ja  v a 2  s . c om
    }
    this.started = true;
    final StringBuffer info = new StringBuffer("RemotingController...\n");
    info.append("\n").append(this.config.toString());
    log.info(info.toString());
    if (this.remotingContext == null) {
        this.remotingContext = new DefaultRemotingContext(this.config,
                this.config.getWireFormatType().newCommandFactory());
    } else {
        // processorlistener
        this.remotingContext.dispose();
        final ConcurrentHashMap<Class<? extends RequestCommand>, RequestProcessor<? extends RequestCommand>> processorMap = this.remotingContext.processorMap;
        final CopyOnWriteArrayList<ConnectionLifeCycleListener> connectionLifeCycleListenerList = this.remotingContext.connectionLifeCycleListenerList;
        this.remotingContext = new DefaultRemotingContext(this.remotingContext.getConfig(),
                this.config.getWireFormatType().newCommandFactory());
        this.remotingContext.processorMap.putAll(processorMap);
        this.remotingContext.connectionLifeCycleListenerList.addAll(connectionLifeCycleListenerList);
    }
    final Configuration conf = this.getConfigurationFromConfig(this.config);
    this.controller = this.initController(conf);
    this.controller.setCodecFactory(this.config.getWireFormatType().newCodecFactory());
    this.controller.setHandler(new GeckoHandler(this));
    this.controller.setSoLinger(this.config.isSoLinger(), this.config.getLinger());
    this.controller.setSocketOptions(this.getSocketOptionsFromConfig(this.config));
    this.controller.setSelectorPoolSize(this.config.getSelectorPoolSize());
    this.scanAllConnectionExecutor = Executors
            .newSingleThreadScheduledExecutor(new WorkerThreadFactory("notify-remoting-ScanAllConnection"));
    if (this.config.getScanAllConnectionInterval() > 0) {
        this.scanAllConnectionExecutor.scheduleAtFixedRate(
                new ScanAllConnectionRunner(this, this.getScanTasks()), 1,
                this.config.getScanAllConnectionInterval(), TimeUnit.SECONDS);
    }
    this.doStart();
    this.addShutdownHook();
}

From source file:org.apache.bookkeeper.stats.prometheus.PrometheusMetricsProvider.java

@Override
public void start(Configuration conf) {
    boolean httpEnabled = conf.getBoolean(PROMETHEUS_STATS_HTTP_ENABLE, DEFAULT_PROMETHEUS_STATS_HTTP_ENABLE);
    boolean bkHttpServerEnabled = conf.getBoolean("httpServerEnabled", false);
    // only start its own http server when prometheus http is enabled and bk http server is not enabled.
    if (httpEnabled && !bkHttpServerEnabled) {
        int httpPort = conf.getInt(PROMETHEUS_STATS_HTTP_PORT, DEFAULT_PROMETHEUS_STATS_HTTP_PORT);
        InetSocketAddress httpEndpoint = InetSocketAddress.createUnresolved("0.0.0.0", httpPort);
        this.server = new Server(httpEndpoint);
        ServletContextHandler context = new ServletContextHandler();
        context.setContextPath("/");
        server.setHandler(context);//from   w  w  w  .j av  a  2s .c om

        context.addServlet(new ServletHolder(new PrometheusServlet(this)), "/metrics");

        try {
            server.start();
            log.info("Started Prometheus stats endpoint at {}", httpEndpoint);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // Include standard JVM stats
    registerMetrics(new StandardExports());
    registerMetrics(new MemoryPoolsExports());
    registerMetrics(new GarbageCollectorExports());
    registerMetrics(new ThreadExports());

    // Add direct memory allocated through unsafe
    registerMetrics(Gauge.build("jvm_memory_direct_bytes_used", "-").create().setChild(new Child() {
        @Override
        public double get() {
            return directMemoryUsage != null ? directMemoryUsage.longValue() : Double.NaN;
        }
    }));

    registerMetrics(Gauge.build("jvm_memory_direct_bytes_max", "-").create().setChild(new Child() {
        @Override
        public double get() {
            return PlatformDependent.maxDirectMemory();
        }
    }));

    executor = Executors.newSingleThreadScheduledExecutor(new DefaultThreadFactory("metrics"));

    int latencyRolloverSeconds = conf.getInt(PROMETHEUS_STATS_LATENCY_ROLLOVER_SECONDS,
            DEFAULT_PROMETHEUS_STATS_LATENCY_ROLLOVER_SECONDS);

    executor.scheduleAtFixedRate(() -> {
        rotateLatencyCollection();
    }, 1, latencyRolloverSeconds, TimeUnit.SECONDS);

}

From source file:com.alibaba.napoli.gecko.service.impl.BaseRemotingController.java

public final synchronized void start() throws NotifyRemotingException {
    if (this.started) {
        return;/*  ww  w.ja  v a 2  s  .  c  o  m*/
    }
    this.started = true;
    final StringBuffer info = new StringBuffer("??RemotingController...\n");
    info.append("?\n").append(this.config.toString());
    log.info(info.toString());
    if (this.remotingContext == null) {
        this.remotingContext = new DefaultRemotingContext(this.config,
                this.config.getWireFormatType().newCommandFactory());
    } else {
        // ?processorlistener
        this.remotingContext.dispose();
        final ConcurrentHashMap<Class<? extends RequestCommand>, RequestProcessor<? extends RequestCommand>> processorMap = this.remotingContext.processorMap;
        final CopyOnWriteArrayList<ConnectionLifeCycleListener> connectionLifeCycleListenerList = this.remotingContext.connectionLifeCycleListenerList;
        this.remotingContext = new DefaultRemotingContext(this.remotingContext.getConfig(),
                this.config.getWireFormatType().newCommandFactory());
        this.remotingContext.processorMap.putAll(processorMap);
        this.remotingContext.connectionLifeCycleListenerList.addAll(connectionLifeCycleListenerList);
    }
    final Configuration conf = this.getConfigurationFromConfig(this.config);
    this.controller = this.initController(conf);
    this.controller.setCodecFactory(this.config.getWireFormatType().newCodecFactory());
    this.controller.setHandler(new GeckoHandler(this));
    this.controller.setSoLinger(this.config.isSoLinger(), this.config.getLinger());
    this.controller.setSocketOptions(this.getSocketOptionsFromConfig(this.config));
    this.controller.setSelectorPoolSize(this.config.getSelectorPoolSize());
    this.scanAllConnectionExecutor = Executors
            .newSingleThreadScheduledExecutor(new WorkerThreadFactory("notify-remoting-ScanAllConnection"));
    this.scanAllConnectionExecutor.scheduleAtFixedRate(new ScanAllConnectionRunner(this, this.getScanTasks()),
            1, this.config.getScanAllConnectionInterval(), TimeUnit.SECONDS);
    this.doStart();
    this.addShutdownHook();
}

From source file:com.arpnetworking.metrics.mad.Main.java

private void launchJvmMetricsCollector(final Injector injector) {
    LOGGER.info().setMessage("Launching JVM metrics collector.").log();
    final Runnable runnable = new JvmMetricsRunnable.Builder()
            .setMetricsFactory(injector.getInstance(MetricsFactory.class)).build();
    _jvmMetricsCollector = Executors
            .newSingleThreadScheduledExecutor((r) -> new Thread(r, "JVMMetricsCollector"));
    _jvmMetricsCollector.scheduleAtFixedRate(runnable, INITIAL_DELAY_IN_MILLIS,
            _configuration.getJvmMetricsCollectionInterval().toStandardDuration().getMillis(), TIME_UNIT);
}

From source file:com.reactivetechnologies.analytics.core.IncrementalClassifierBean.java

@PostConstruct
void init() {//from   ww  w  .  j  a  v a  2  s .co  m
    loadAndInitializeModel();

    log.info((isUpdateable() ? "UPDATEABLE " : "NON-UPDATEABLE ") + "** Weka Classifier loaded [" + clazzifier
            + "] **");
    if (log.isDebugEnabled()) {
        log.debug("weka.classifier.tokenize? " + filterDataset);
        log.debug("weka.classifier.tokenize.options: " + filterOpts);
        log.debug("weka.classifier.build.batchSize: " + instanceBatchSize);
        log.debug("weka.classifier.build.intervalSecs: " + delay);
        log.debug("weka.classifier.build.maxIdleSecs: " + maxIdle);
    }
    worker = Executors.newSingleThreadExecutor(new ThreadFactory() {

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r, "RegressionBean.Worker.Thread");
            return t;
        }
    });
    worker.submit(new EventConsumer());

    timer = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r, "RegressionBean.Timer.Thread");
            t.setDaemon(true);
            return t;
        }
    });
    ((ScheduledExecutorService) timer).scheduleWithFixedDelay(new EventTimer(), delay, delay, TimeUnit.SECONDS);
}