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:org.apache.flume.channel.file.Log.java

private Log(long checkpointInterval, long maxFileSize, int queueCapacity, int logWriteTimeout,
        int checkpointWriteTimeout, boolean useDualCheckpoints, File checkpointDir, File backupCheckpointDir,
        String name, boolean useLogReplayV1, boolean useFastReplay, long minimumRequiredSpace,
        @Nullable KeyProvider encryptionKeyProvider, @Nullable String encryptionKeyAlias,
        @Nullable String encryptionCipherProvider, long usableSpaceRefreshInterval, File... logDirs)
        throws IOException {
    Preconditions.checkArgument(checkpointInterval > 0, "checkpointInterval <= 0");
    Preconditions.checkArgument(queueCapacity > 0, "queueCapacity <= 0");
    Preconditions.checkArgument(maxFileSize > 0, "maxFileSize <= 0");
    Preconditions.checkNotNull(checkpointDir, "checkpointDir");
    Preconditions.checkArgument(usableSpaceRefreshInterval > 0, "usableSpaceRefreshInterval <= 0");
    Preconditions.checkArgument(checkpointDir.isDirectory() || checkpointDir.mkdirs(),
            "CheckpointDir " + checkpointDir + " could not be created");
    if (useDualCheckpoints) {
        Preconditions.checkNotNull(backupCheckpointDir,
                "backupCheckpointDir is" + " null while dual checkpointing is enabled.");
        Preconditions.checkArgument(backupCheckpointDir.isDirectory() || backupCheckpointDir.mkdirs(),
                "Backup CheckpointDir " + backupCheckpointDir + " could not be created");
    }/*from  w  w w  .ja v a 2 s . co m*/
    Preconditions.checkNotNull(logDirs, "logDirs");
    Preconditions.checkArgument(logDirs.length > 0, "logDirs empty");
    Preconditions.checkArgument(name != null && !name.trim().isEmpty(), "channel name should be specified");

    this.channelNameDescriptor = "[channel=" + name + "]";
    this.useLogReplayV1 = useLogReplayV1;
    this.useFastReplay = useFastReplay;
    this.minimumRequiredSpace = minimumRequiredSpace;
    this.usableSpaceRefreshInterval = usableSpaceRefreshInterval;
    for (File logDir : logDirs) {
        Preconditions.checkArgument(logDir.isDirectory() || logDir.mkdirs(),
                "LogDir " + logDir + " could not be created");
    }
    locks = Maps.newHashMap();
    try {
        lock(checkpointDir);
        if (useDualCheckpoints) {
            lock(backupCheckpointDir);
        }
        for (File logDir : logDirs) {
            lock(logDir);
        }
    } catch (IOException e) {
        unlock(checkpointDir);
        for (File logDir : logDirs) {
            unlock(logDir);
        }
        throw e;
    }
    if (encryptionKeyProvider != null && encryptionKeyAlias != null && encryptionCipherProvider != null) {
        LOGGER.info("Encryption is enabled with encryptionKeyProvider = " + encryptionKeyProvider
                + ", encryptionKeyAlias = " + encryptionKeyAlias + ", encryptionCipherProvider = "
                + encryptionCipherProvider);
        this.encryptionKeyProvider = encryptionKeyProvider;
        this.encryptionKeyAlias = encryptionKeyAlias;
        this.encryptionCipherProvider = encryptionCipherProvider;
        this.encryptionKey = encryptionKeyProvider.getKey(encryptionKeyAlias);
    } else if (encryptionKeyProvider == null && encryptionKeyAlias == null
            && encryptionCipherProvider == null) {
        LOGGER.info("Encryption is not enabled");
    } else {
        throw new IllegalArgumentException(
                "Encryption configuration must all " + "null or all not null: encryptionKeyProvider = "
                        + encryptionKeyProvider + ", encryptionKeyAlias = " + encryptionKeyAlias
                        + ", encryptionCipherProvider = " + encryptionCipherProvider);
    }
    open = false;
    this.checkpointInterval = Math.max(checkpointInterval, 1000);
    this.maxFileSize = maxFileSize;
    this.queueCapacity = queueCapacity;
    this.useDualCheckpoints = useDualCheckpoints;
    this.checkpointDir = checkpointDir;
    this.backupCheckpointDir = backupCheckpointDir;
    this.logDirs = logDirs;
    this.logWriteTimeout = logWriteTimeout;
    this.checkpointWriteTimeout = checkpointWriteTimeout;
    logFiles = new AtomicReferenceArray<LogFile.Writer>(this.logDirs.length);
    workerExecutor = Executors.newSingleThreadScheduledExecutor(
            new ThreadFactoryBuilder().setNameFormat("Log-BackgroundWorker-" + name).build());
    workerExecutor.scheduleWithFixedDelay(new BackgroundWorker(this), this.checkpointInterval,
            this.checkpointInterval, TimeUnit.MILLISECONDS);
}

From source file:com.all.ultrapeer.services.PresenceService.java

@PreDestroy
@MessageMethod(STOP_ULTRAPEER_SERVICES_TYPE)
public synchronized void stop() {
    if (!started.get()) {
        return;/*from www . j  a v a2  s  .c  o m*/
    }
    updateGlobalOnlineUsers();
    globalPresenceExecutor.shutdownNow();
    localOnlineUsers.clear();
    globalPresenceExecutor = Executors
            .newSingleThreadScheduledExecutor(new IncrementalNamedThreadFactory("GlobalPresenceThread"));
    started.set(false);
    log.info("PresenceService succesfully stopped.");
}

From source file:org.apache.hadoop.hive.metastore.ReplChangeManager.java

static void scheduleCMClearer(HiveConf hiveConf) {
    if (HiveConf.getBoolVar(hiveConf, HiveConf.ConfVars.REPLCMENABLED)) {
        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(
                new BasicThreadFactory.Builder().namingPattern("cmclearer-%d").daemon(true).build());
        executor.scheduleAtFixedRate(//from  w w w  .j  a  v  a 2 s  .  co  m
                new CMClearer(hiveConf.get(HiveConf.ConfVars.REPLCMDIR.varname),
                        hiveConf.getTimeVar(ConfVars.REPLCMRETIAN, TimeUnit.SECONDS), hiveConf),
                0, hiveConf.getTimeVar(ConfVars.REPLCMINTERVAL, TimeUnit.SECONDS), TimeUnit.SECONDS);
    }
}

From source file:org.mule.module.launcher.application.DefaultMuleApplication.java

protected void scheduleConfigMonitor(AbstractFileWatcher watcher) {
    final int reloadIntervalMs = DEFAULT_RELOAD_CHECK_INTERVAL_MS;
    watchTimer = Executors
            .newSingleThreadScheduledExecutor(new ConfigChangeMonitorThreadFactory(descriptor.getAppName()));

    watchTimer.scheduleWithFixedDelay(watcher, reloadIntervalMs, reloadIntervalMs, TimeUnit.MILLISECONDS);

    if (logger.isInfoEnabled()) {
        logger.info("Reload interval: " + reloadIntervalMs);
    }//w  w  w.  java 2s.com
}

From source file:net.dv8tion.jda.core.audio.AudioConnection.java

private synchronized void setupCombinedExecutor() {
    if (combinedAudioExecutor == null) {
        combinedAudioExecutor = Executors.newSingleThreadScheduledExecutor(
                r -> new Thread(AudioManagerImpl.AUDIO_THREADS, r, threadIdentifier + " Combined Thread"));
        combinedAudioExecutor.scheduleAtFixedRate(() -> {
            try {
                List<User> users = new LinkedList<>();
                List<short[]> audioParts = new LinkedList<>();
                if (receiveHandler != null && receiveHandler.canReceiveCombined()) {
                    long currentTime = System.currentTimeMillis();
                    for (Map.Entry<User, Queue<Pair<Long, short[]>>> entry : combinedQueue.entrySet()) {
                        User user = entry.getKey();
                        Queue<Pair<Long, short[]>> queue = entry.getValue();

                        if (queue.isEmpty())
                            continue;

                        Pair<Long, short[]> audioData = queue.poll();
                        //Make sure the audio packet is younger than 100ms
                        while (audioData != null && currentTime - audioData.getLeft() > queueTimeout) {
                            audioData = queue.poll();
                        }//w  ww  .jav a 2  s . com

                        //If none of the audio packets were younger than 100ms, then there is nothing to add.
                        if (audioData == null) {
                            continue;
                        }
                        users.add(user);
                        audioParts.add(audioData.getRight());
                    }

                    if (!audioParts.isEmpty()) {
                        int audioLength = audioParts.get(0).length;
                        short[] mix = new short[1920]; //960 PCM samples for each channel
                        int sample;
                        for (int i = 0; i < audioLength; i++) {
                            sample = 0;
                            for (short[] audio : audioParts) {
                                sample += audio[i];
                            }
                            if (sample > Short.MAX_VALUE)
                                mix[i] = Short.MAX_VALUE;
                            else if (sample < Short.MIN_VALUE)
                                mix[i] = Short.MIN_VALUE;
                            else
                                mix[i] = (short) sample;
                        }
                        receiveHandler.handleCombinedAudio(new CombinedAudio(users, mix));
                    } else {
                        //No audio to mix, provide 20 MS of silence. (960 PCM samples for each channel)
                        receiveHandler.handleCombinedAudio(
                                new CombinedAudio(Collections.emptyList(), new short[1920]));
                    }
                }
            } catch (Exception e) {
                LOG.log(e);
            }
        }, 0, 20, TimeUnit.MILLISECONDS);
    }
}

From source file:org.apache.hedwig.server.netty.PubSubServer.java

public void start() throws Exception {
    final SynchronousQueue<Either<Object, Exception>> queue = new SynchronousQueue<Either<Object, Exception>>();

    new Thread(tg, new Runnable() {
        @Override/*from w  ww .j av  a  2s.c o  m*/
        public void run() {
            try {
                // Since zk is needed by almost everyone,try to see if we
                // need that first
                ThreadFactoryBuilder tfb = new ThreadFactoryBuilder();
                scheduler = Executors.newSingleThreadScheduledExecutor(
                        tfb.setNameFormat("PubSubServerScheduler-%d").build());
                serverChannelFactory = new NioServerSocketChannelFactory(
                        Executors.newCachedThreadPool(tfb.setNameFormat("PubSub-Server-NIOBoss-%d").build()),
                        Executors.newCachedThreadPool(tfb.setNameFormat("PubSub-Server-NIOWorker-%d").build()));
                clientChannelFactory = new NioClientSocketChannelFactory(
                        Executors.newCachedThreadPool(tfb.setNameFormat("PubSub-Client-NIOBoss-%d").build()),
                        Executors.newCachedThreadPool(tfb.setNameFormat("PubSub-Client-NIOWorker-%d").build()));

                instantiateZookeeperClient();
                instantiateMetadataManagerFactory();
                tm = instantiateTopicManager();
                pm = instantiatePersistenceManager(tm);
                dm = new FIFODeliveryManager(tm, pm, conf);
                dm.start();

                sm = instantiateSubscriptionManager(tm, pm, dm);
                rm = instantiateRegionManager(pm, scheduler);
                sm.addListener(rm);

                allChannels = new DefaultChannelGroup("hedwig");
                // Initialize the Netty Handlers (used by the
                // UmbrellaHandler) once so they can be shared by
                // both the SSL and non-SSL channels.
                SubscriptionChannelManager subChannelMgr = new SubscriptionChannelManager();
                subChannelMgr.addSubChannelDisconnectedListener((SubChannelDisconnectedListener) dm);
                Map<OperationType, Handler> handlers = initializeNettyHandlers(tm, dm, pm, sm, subChannelMgr);
                // Initialize Netty for the regular non-SSL channels
                initializeNetty(null, handlers, subChannelMgr);
                if (conf.isSSLEnabled()) {
                    initializeNetty(new SslServerContextFactory(conf), handlers, subChannelMgr);
                }
                // register jmx
                registerJMX(subChannelMgr);
            } catch (Exception e) {
                ConcurrencyUtils.put(queue, Either.right(e));
                return;
            }

            ConcurrencyUtils.put(queue, Either.of(new Object(), (Exception) null));
        }

    }).start();

    Either<Object, Exception> either = ConcurrencyUtils.take(queue);
    if (either.left() == null) {
        throw either.right();
    }
}

From source file:net.dv8tion.jda.audio.AudioConnection.java

private void setupCombinedExecutor() {
    if (combinedAudioExecutor == null) {
        combinedAudioExecutor = Executors.newSingleThreadScheduledExecutor(
                r -> new Thread(r, "AudioConnection CombinedAudio Guild: " + channel.getGuild().getId()));
        combinedAudioExecutor.scheduleAtFixedRate(() -> {
            try {
                List<User> users = new LinkedList<>();
                List<short[]> audioParts = new LinkedList<>();
                if (receiveHandler != null && receiveHandler.canReceiveCombined()) {
                    long currentTime = System.currentTimeMillis();
                    for (Map.Entry<User, Queue<Pair<Long, short[]>>> entry : combinedQueue.entrySet()) {
                        User user = entry.getKey();
                        Queue<Pair<Long, short[]>> queue = entry.getValue();

                        if (queue.isEmpty())
                            continue;

                        Pair<Long, short[]> audioData = queue.poll();
                        //Make sure the audio packet is younger than 100ms
                        while (audioData != null && currentTime - audioData.getLeft() > queueTimeout) {
                            audioData = queue.poll();
                        }// www. ja va 2 s  .  c om

                        //If none of the audio packets were younger than 100ms, then there is nothing to add.
                        if (audioData == null) {
                            continue;
                        }
                        users.add(user);
                        audioParts.add(audioData.getRight());
                    }

                    if (!audioParts.isEmpty()) {
                        int audioLength = audioParts.get(0).length;
                        short[] mix = new short[1920]; //960 PCM samples for each channel
                        int sample;
                        for (int i = 0; i < audioLength; i++) {
                            sample = 0;
                            for (short[] audio : audioParts) {
                                sample += audio[i];
                            }
                            if (sample > Short.MAX_VALUE)
                                mix[i] = Short.MAX_VALUE;
                            else if (sample < Short.MIN_VALUE)
                                mix[i] = Short.MIN_VALUE;
                            else
                                mix[i] = (short) sample;
                        }
                        receiveHandler.handleCombinedAudio(new CombinedAudio(users, mix));
                    } else {
                        //No audio to mix, provide 20 MS of silence. (960 PCM samples for each channel)
                        receiveHandler
                                .handleCombinedAudio(new CombinedAudio(new LinkedList(), new short[1920]));
                    }
                }
            } catch (Exception e) {
                LOG.log(e);
            }
        }, 0, 20, TimeUnit.MILLISECONDS);
    }
}

From source file:com.datatorrent.contrib.hdht.HDHTWriter.java

@Override
public void setup(OperatorContext context) {
    super.setup(context);
    if (context != null) {
        setWalKey(context.getId());/* w ww  .jav  a 2s  .  com*/
    }
    writeExecutor = Executors.newSingleThreadScheduledExecutor(
            new NameableThreadFactory(this.getClass().getSimpleName() + "-Writer"));

    this.context = context;
    if (this.walStore == null) {
        // if WAL location is not specified, by default it would be placed under <HDHT Location>/WAL/ if HDHT location is known
        // Otherwise default location is under <Application Path>/WAL/
        this.walStore = new TFileImpl.DTFileImpl();
        if (this.store instanceof FileAccessFSImpl) {
            ((FileAccessFSImpl) this.walStore)
                    .setBasePath(((FileAccessFSImpl) this.store).getBasePath() + WAL_FILES_LOCATION);
        } else {
            ((FileAccessFSImpl) this.walStore)
                    .setBasePath(context.getValue(DAG.APPLICATION_PATH) + WAL_FILES_LOCATION);
        }
    }
    this.walStore.init();

    if (!this.parentWals.isEmpty()) {
        if (this.parentWals.size() == 1) {
            PreviousWALDetails parentWal = parentWals.iterator().next();
            this.singleWalMeta = new WalMeta(parentWal.getWindowId(), parentWal.getEndPosition());
        } else {
            this.singleWalMeta.cpWalPosition = new WalPosition(0, 0);
        }
    }
    this.wal = new HDHTWalManager(this.walStore, getWalKey(), this.singleWalMeta.cpWalPosition);
    this.wal.setMaxWalFileSize(maxWalFileSize);

    if (!this.parentWals.isEmpty()) {
        resetBucketMeta();
        if (this.parentWals.size() == 1) {
            // Copy the WAL files as is from parent WAL
            this.walPositions = parentWals.iterator().next().walPositions;
            this.wal.copyPreviousWalFiles(parentWals, alreadyCopiedWals);
            alreadyCopiedWals.addAll(parentWals);
            parentWals.clear();
        } else {
            mergeParentWalFilesByWindow();
        }
    }
}

From source file:com.mustardgrain.solr.SolrClient.java

private void startAliveCheckExecutor() {
    // double-checked locking, but it's OK because we don't *do* anything
    // with aliveCheckExecutor
    // if it's not null.
    if (aliveCheckExecutor == null) {
        synchronized (this) {
            if (aliveCheckExecutor == null) {
                aliveCheckExecutor = Executors
                        .newSingleThreadScheduledExecutor(new SolrjNamedThreadFactory("aliveCheckExecutor"));
                aliveCheckExecutor.scheduleAtFixedRate(getAliveCheckRunner(new WeakReference<SolrClient>(this)),
                        this.interval, this.interval, TimeUnit.MILLISECONDS);
            }//from ww w  .ja  v a  2  s . co  m
        }
    }
}

From source file:org.apache.solr.client.solrj.impl.LBHttpSolrClient.java

private void startAliveCheckExecutor() {
    // double-checked locking, but it's OK because we don't *do* anything with aliveCheckExecutor
    // if it's not null.
    if (aliveCheckExecutor == null) {
        synchronized (this) {
            if (aliveCheckExecutor == null) {
                aliveCheckExecutor = Executors
                        .newSingleThreadScheduledExecutor(new SolrjNamedThreadFactory("aliveCheckExecutor"));
                aliveCheckExecutor.scheduleAtFixedRate(getAliveCheckRunner(new WeakReference<>(this)),
                        this.interval, this.interval, TimeUnit.MILLISECONDS);
            }/*  w w w  .  j a v  a  2s .co m*/
        }
    }
}