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() 

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.hama.monitor.fd.UDPSupervisor.java

/**
 * UDP Supervisor.//from   w  w w. jav a  2s .  c om
 */
public UDPSupervisor(HamaConfiguration conf) {
    DatagramChannel ch = null;
    try {
        ch = DatagramChannel.open();
    } catch (IOException ioe) {
        LOG.error("Fail to open udp channel.", ioe);
    }
    this.channel = ch;
    if (null == this.channel)
        throw new NullPointerException("Channel can not be opened.");
    try {
        this.channel.socket().bind(new InetSocketAddress(conf.getInt("bsp.monitor.fd.udp_port", 16384)));
    } catch (SocketException se) {
        LOG.error("Unable to bind the udp socket.", se);
    }
    WINDOW_SIZE.set(conf.getInt("bsp.monitor.fd.window_size", 100));
    this.receiver = Executors.newCachedThreadPool();
    this.supervisor = Executors.newSingleThreadExecutor();
    this.watcher = Executors.newSingleThreadScheduledExecutor();
}

From source file:org.elasticsearch.client.sniff.SnifferTests.java

/**
 * Test behaviour when a bunch of onFailure sniffing rounds are triggered in parallel. Each run will always
 * schedule a subsequent afterFailure round. Also, for each onFailure round that starts, the net scheduled round
 * (either afterFailure or ordinary) gets cancelled.
 *///from ww w. j  a v  a2  s.  c  o  m
public void testSniffOnFailure() throws Exception {
    RestClient restClient = mock(RestClient.class);
    CountingHostsSniffer hostsSniffer = new CountingHostsSniffer();
    final AtomicBoolean initializing = new AtomicBoolean(true);
    final long sniffInterval = randomLongBetween(1, Long.MAX_VALUE);
    final long sniffAfterFailureDelay = randomLongBetween(1, Long.MAX_VALUE);
    int minNumOnFailureRounds = randomIntBetween(5, 10);
    final CountDownLatch initializingLatch = new CountDownLatch(1);
    final Set<Sniffer.ScheduledTask> ordinaryRoundsTasks = new CopyOnWriteArraySet<>();
    final AtomicReference<Future<?>> initializingFuture = new AtomicReference<>();
    final Set<Sniffer.ScheduledTask> onFailureTasks = new CopyOnWriteArraySet<>();
    final Set<Sniffer.ScheduledTask> afterFailureTasks = new CopyOnWriteArraySet<>();
    final AtomicBoolean onFailureCompleted = new AtomicBoolean(false);
    final CountDownLatch completionLatch = new CountDownLatch(1);
    final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    try {
        Scheduler scheduler = new Scheduler() {
            @Override
            public Future<?> schedule(final Sniffer.Task task, long delayMillis) {
                if (initializing.compareAndSet(true, false)) {
                    assertEquals(0L, delayMillis);
                    Future<?> future = executor.submit(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                task.run();
                            } finally {
                                //we need to make sure that the sniffer is initialized, so the sniffOnFailure
                                //call does what it needs to do. Otherwise nothing happens until initialized.
                                initializingLatch.countDown();
                            }
                        }
                    });
                    assertTrue(initializingFuture.compareAndSet(null, future));
                    return future;
                }
                if (delayMillis == 0L) {
                    Future<?> future = executor.submit(task);
                    onFailureTasks.add(new Sniffer.ScheduledTask(task, future));
                    return future;
                }
                if (delayMillis == sniffAfterFailureDelay) {
                    Future<?> future = scheduleOrSubmit(task);
                    afterFailureTasks.add(new Sniffer.ScheduledTask(task, future));
                    return future;
                }

                assertEquals(sniffInterval, delayMillis);
                assertEquals(sniffInterval, task.nextTaskDelay);

                if (onFailureCompleted.get() && onFailureTasks.size() == afterFailureTasks.size()) {
                    completionLatch.countDown();
                    return mock(Future.class);
                }

                Future<?> future = scheduleOrSubmit(task);
                ordinaryRoundsTasks.add(new Sniffer.ScheduledTask(task, future));
                return future;
            }

            private Future<?> scheduleOrSubmit(Sniffer.Task task) {
                if (randomBoolean()) {
                    return executor.schedule(task, randomLongBetween(0L, 200L), TimeUnit.MILLISECONDS);
                } else {
                    return executor.submit(task);
                }
            }

            @Override
            public void shutdown() {
            }
        };
        final Sniffer sniffer = new Sniffer(restClient, hostsSniffer, scheduler, sniffInterval,
                sniffAfterFailureDelay);
        assertTrue("timeout waiting for sniffer to get initialized",
                initializingLatch.await(1000, TimeUnit.MILLISECONDS));

        ExecutorService onFailureExecutor = Executors.newFixedThreadPool(randomIntBetween(5, 20));
        Set<Future<?>> onFailureFutures = new CopyOnWriteArraySet<>();
        try {
            //with tasks executing quickly one after each other, it is very likely that the onFailure round gets skipped
            //as another round is already running. We retry till enough runs get through as that's what we want to test.
            while (onFailureTasks.size() < minNumOnFailureRounds) {
                onFailureFutures.add(onFailureExecutor.submit(new Runnable() {
                    @Override
                    public void run() {
                        sniffer.sniffOnFailure();
                    }
                }));
            }
            assertThat(onFailureFutures.size(), greaterThanOrEqualTo(minNumOnFailureRounds));
            for (Future<?> onFailureFuture : onFailureFutures) {
                assertNull(onFailureFuture.get());
            }
            onFailureCompleted.set(true);
        } finally {
            onFailureExecutor.shutdown();
            onFailureExecutor.awaitTermination(1000, TimeUnit.MILLISECONDS);
        }

        assertFalse(initializingFuture.get().isCancelled());
        assertTrue(initializingFuture.get().isDone());
        assertNull(initializingFuture.get().get());

        assertTrue("timeout waiting for sniffing rounds to be completed",
                completionLatch.await(1000, TimeUnit.MILLISECONDS));
        assertThat(onFailureTasks.size(), greaterThanOrEqualTo(minNumOnFailureRounds));
        assertEquals(onFailureTasks.size(), afterFailureTasks.size());

        for (Sniffer.ScheduledTask onFailureTask : onFailureTasks) {
            assertFalse(onFailureTask.future.isCancelled());
            assertTrue(onFailureTask.future.isDone());
            assertNull(onFailureTask.future.get());
            assertTrue(onFailureTask.task.hasStarted());
            assertFalse(onFailureTask.task.isSkipped());
        }

        int cancelledTasks = 0;
        int completedTasks = onFailureTasks.size() + 1;
        for (Sniffer.ScheduledTask afterFailureTask : afterFailureTasks) {
            if (assertTaskCancelledOrCompleted(afterFailureTask)) {
                completedTasks++;
            } else {
                cancelledTasks++;
            }
        }

        assertThat(ordinaryRoundsTasks.size(), greaterThan(0));
        for (Sniffer.ScheduledTask task : ordinaryRoundsTasks) {
            if (assertTaskCancelledOrCompleted(task)) {
                completedTasks++;
            } else {
                cancelledTasks++;
            }
        }
        assertEquals(onFailureTasks.size(), cancelledTasks);

        assertEquals(completedTasks, hostsSniffer.runs.get());
        int setHostsRuns = hostsSniffer.runs.get() - hostsSniffer.failures.get() - hostsSniffer.emptyList.get();
        verify(restClient, times(setHostsRuns)).setHosts(Matchers.<HttpHost>anyVararg());
        verifyNoMoreInteractions(restClient);
    } finally {
        executor.shutdown();
        executor.awaitTermination(1000L, TimeUnit.MILLISECONDS);
    }
}

From source file:org.eclipse.jdt.ls.core.internal.handlers.JDTLanguageServer.java

@Override
public void exit() {
    logInfo(">> exit");
    JavaLanguageServerPlugin.getLanguageServer().exit();
    Executors.newSingleThreadScheduledExecutor().schedule(() -> {
        logInfo("Forcing exit after 1 min.");
        System.exit(FORCED_EXIT_CODE);
    }, 1, TimeUnit.MINUTES);/*from   ww  w.  j  ava 2  s.c  o m*/
}

From source file:com.web.server.EARDeployer.java

/**
 * This method configures the executor services from the jar file.
 * // w  w w.  j  a v a 2  s.co  m
 * @param jarFile
 * @param classList
 * @throws FileSystemException
 */
public void deployExecutorServicesEar(String earFileName, FileObject earFile,
        StandardFileSystemManager fsManager) throws FileSystemException {
    try {
        System.out.println("EARFILE NAMEs=" + earFileName);
        CopyOnWriteArrayList<FileObject> fileObjects = new CopyOnWriteArrayList<FileObject>();
        CopyOnWriteArrayList<FileObject> warObjects = new CopyOnWriteArrayList<FileObject>();
        ConcurrentHashMap jarClassListMap = new ConcurrentHashMap();
        CopyOnWriteArrayList<String> classList;
        obtainUrls(earFile, earFile, fileObjects, jarClassListMap, warObjects, fsManager);
        VFSClassLoader customClassLoaderBaseLib = new VFSClassLoader(
                fileObjects.toArray(new FileObject[fileObjects.size()]), fsManager,
                Thread.currentThread().getContextClassLoader());
        VFSClassLoader customClassLoader = null;
        Set keys = jarClassListMap.keySet();
        Iterator key = keys.iterator();
        FileObject jarFileObject;
        ConcurrentHashMap classLoaderPath = new ConcurrentHashMap();
        filesMap.put(earFileName, classLoaderPath);
        for (FileObject warFileObj : warObjects) {
            if (warFileObj.getName().getBaseName().endsWith(".war")) {
                //logger.info("filePath"+filePath);
                String filePath = scanDirectory + "/" + warFileObj.getName().getBaseName();
                log.info(filePath);
                String fileName = warFileObj.getName().getBaseName();
                WebClassLoader classLoader = new WebClassLoader(new URL[] {});
                log.info(classLoader);
                warDeployer.deleteDir(
                        new File(deployDirectory + "/" + fileName.substring(0, fileName.lastIndexOf(".war"))));
                new File(deployDirectory + "/" + fileName.substring(0, fileName.lastIndexOf(".war"))).mkdirs();
                log.info(deployDirectory + "/" + fileName.substring(0, fileName.lastIndexOf(".war")));
                urlClassLoaderMap.put(
                        deployDirectory + "/" + fileName.substring(0, fileName.lastIndexOf(".war")),
                        classLoader);
                classLoaderPath.put(warFileObj.getName().getBaseName(),
                        deployDirectory + "/" + fileName.substring(0, fileName.lastIndexOf(".war")));
                warDeployer.extractWar(new File(filePath), classLoader);

                if (exec != null) {
                    exec.shutdown();
                }
                new File(scanDirectory + "/" + warFileObj.getName().getBaseName()).delete();
                exec = Executors.newSingleThreadScheduledExecutor();
                exec.scheduleAtFixedRate(task, 0, 1000, TimeUnit.MILLISECONDS);
            }
        }
        for (int keyCount = 0; keyCount < keys.size(); keyCount++) {
            jarFileObject = (FileObject) key.next();
            {
                classList = (CopyOnWriteArrayList<String>) jarClassListMap.get(jarFileObject);
                customClassLoader = new VFSClassLoader(jarFileObject, fsManager, customClassLoaderBaseLib);
                this.urlClassLoaderMap.put(
                        scanDirectory + "/" + earFileName + "/" + jarFileObject.getName().getBaseName(),
                        customClassLoader);
                classLoaderPath.put(jarFileObject.getName().getBaseName(),
                        scanDirectory + "/" + earFileName + "/" + jarFileObject.getName().getBaseName());
                for (int classCount = 0; classCount < classList.size(); classCount++) {
                    String classwithpackage = classList.get(classCount).substring(0,
                            classList.get(classCount).indexOf(".class"));
                    classwithpackage = classwithpackage.replace("/", ".");
                    // System.out.println("classList:"+classwithpackage.replace("/","."));
                    try {
                        if (!classwithpackage.contains("$")) {

                            /*System.out.println("EARFILE NAME="+fileName);
                            System.out
                                  .println(scanDirectory
                            + "/"
                            + fileName
                            + "/"
                            + jarFileObject.getName()
                                  .getBaseName());
                                    
                            System.out.println(urlClassLoaderMap);*/
                            Class executorServiceClass = customClassLoader.loadClass(classwithpackage);

                            Annotation[] classServicesAnnot = executorServiceClass.getDeclaredAnnotations();

                            if (classServicesAnnot != null) {
                                for (int annotcount = 0; annotcount < classServicesAnnot.length; annotcount++) {
                                    if (classServicesAnnot[annotcount] instanceof RemoteCall) {
                                        RemoteCall remoteCall = (RemoteCall) classServicesAnnot[annotcount];
                                        //registry.unbind(remoteCall.servicename());
                                        System.out.println(remoteCall.servicename().trim());
                                        try {
                                            for (int count = 0; count < 2; count++) {
                                                RemoteInterface reminterface = (RemoteInterface) UnicastRemoteObject
                                                        .exportObject(
                                                                (Remote) executorServiceClass.newInstance(), 0);
                                                registry.rebind(remoteCall.servicename().trim(), reminterface);
                                            }
                                        } catch (Exception ex) {
                                            ex.printStackTrace();
                                        }
                                    }
                                }
                            }
                            // System.out.println(executorServiceClass.newInstance());
                            // System.out.println("executor class in ExecutorServicesConstruct"+executorServiceClass);
                            // System.out.println();
                            Method[] methods = executorServiceClass.getDeclaredMethods();
                            for (Method method : methods) {
                                Annotation[] annotations = method.getDeclaredAnnotations();
                                for (Annotation annotation : annotations) {
                                    if (annotation instanceof ExecutorServiceAnnot) {
                                        ExecutorServiceAnnot executorServiceAnnot = (ExecutorServiceAnnot) annotation;
                                        ExecutorServiceInfo executorServiceInfo = new ExecutorServiceInfo();
                                        executorServiceInfo.setExecutorServicesClass(executorServiceClass);
                                        executorServiceInfo.setMethod(method);
                                        executorServiceInfo.setMethodParams(method.getParameterTypes());
                                        //                              System.out.println("serice name="
                                        //                                    + executorServiceAnnot
                                        //                                          .servicename());
                                        //                              System.out.println("method info="
                                        //                                    + executorServiceInfo);
                                        //                              System.out.println(method);
                                        // if(servicesMap.get(executorServiceAnnot.servicename())==null)throw
                                        // new Exception();
                                        executorServiceMap.put(executorServiceAnnot.servicename(),
                                                executorServiceInfo);
                                    }
                                }
                            }
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
            jarFileObject.close();
        }
        for (FileObject fobject : fileObjects) {
            fobject.close();
        }
        System.out.println("Channel unlocked");
        earFile.close();
        fsManager.closeFileSystem(earFile.getFileSystem());
        // ClassLoaderUtil.closeClassLoader(customClassLoader);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:org.apache.metron.profiler.bolt.ProfileBuilderBolt.java

/**
 * Creates a separate thread that regularly flushes expired profiles.
 *///from  w  w  w .j a  v  a2  s  .  c  o m
private void startFlushingExpiredProfiles() {

    long initialDelay = profileTimeToLiveMillis;
    long period = profileTimeToLiveMillis;
    flushExpiredExecutor = Executors.newSingleThreadScheduledExecutor();
    flushExpiredExecutor.scheduleAtFixedRate(() -> flushExpired(), initialDelay, period, TimeUnit.MILLISECONDS);
}

From source file:org.apache.solr.handler.dataimport.ChartSearchDataImportHandler.java

private void runScheduledIndexSizeManager(SolrCore core, IndexClearStrategy clearStrategy, int timeout) {

    indexSizeManager = new IndexSizeManager(core, cache, clearStrategy);

    indexSizeManagerScheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
    indexSizeManagerScheduledExecutorService.scheduleAtFixedRate(new Runnable() {

        @Override/*from   www.j  a  v  a2s.c  o m*/
        public void run() {
            indexSizeManager.clearIndex();
        }
    }, 10, timeout, TimeUnit.SECONDS);

}

From source file:org.apache.solr.handler.dataimport.ChartSearchDataImportHandler.java

private void runScheduledPatientInfoUpdates(int timeout) {
    patientInfoScheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
    patientInfoScheduledExecutorService.scheduleAtFixedRate(new Runnable() {

        @Override/*ww w.  ja v  a2s.  c om*/
        public void run() {
            cache.save();

        }
    }, 10, timeout, TimeUnit.SECONDS);
}

From source file:org.apache.flink.test.recovery.JobManagerHAProcessFailureRecoveryITCase.java

private void waitForTaskManagers(int numberOfTaskManagers, DispatcherGateway dispatcherGateway,
        FiniteDuration timeLeft) throws ExecutionException, InterruptedException {
    FutureUtils.retrySuccessfulWithDelay(
            () -> dispatcherGateway.requestClusterOverview(Time.milliseconds(timeLeft.toMillis())),
            Time.milliseconds(50L),
            org.apache.flink.api.common.time.Deadline.fromNow(Duration.ofMillis(timeLeft.toMillis())),
            clusterOverview -> clusterOverview.getNumTaskManagersConnected() >= numberOfTaskManagers,
            new ScheduledExecutorServiceAdapter(Executors.newSingleThreadScheduledExecutor())).get();
}

From source file:com.emc.ecs.sync.EcsSync.java

private void startPerformanceReporting() {
    if (perfReportSeconds > 0) {
        perfScheduler = Executors.newSingleThreadScheduledExecutor();
        perfScheduler.scheduleAtFixedRate(new Runnable() {
            @Override//from w  ww .  j  a v  a 2  s . c o  m
            public void run() {
                if (isRunning()) {
                    log.info("Source: read: {} b/s write: {} b/s", getSource().getReadRate(),
                            getSource().getWriteRate());
                    log.info("Target: read: {} b/s write: {} b/s", getTarget().getReadRate(),
                            getTarget().getWriteRate());
                    log.info("Objects: complete: {}/s failed: {}/s", getStats().getObjectCompleteRate(),
                            getStats().getObjectErrorRate());
                }
            }
        }, perfReportSeconds, perfReportSeconds, TimeUnit.SECONDS);
    }
}

From source file:net.sourceforge.kalimbaradio.androidapp.activity.DownloadActivity.java

@Override
protected void onResume() {
    super.onResume();

    executorService = Executors.newSingleThreadScheduledExecutor();

    final Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override/*w  ww .j  a va  2  s.  c  o  m*/
        public void run() {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    update();
                }
            });
        }
    };
    executorService.scheduleWithFixedDelay(runnable, 0L, 1000L, TimeUnit.MILLISECONDS);

    setControlsVisible(true);

    DownloadService downloadService = getDownloadService();
    if (downloadService == null || downloadService.getCurrentPlaying() == null) {
        playlistFlipper.setDisplayedChild(1);
    }

    onDownloadListChanged();
    onCurrentChanged();
    onProgressChanged();
    scrollToCurrent();
    if (downloadService != null && downloadService.getKeepScreenOn()) {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    } else {
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    if (visualizerView != null) {
        visualizerView.setActive(downloadService != null && downloadService.getShowVisualization());
    }

    boolean offline = Util.isOffline(this);
    //shareButton.setVisibility(offline ? View.GONE : View.VISIBLE);
    //starButton.setVisibility(offline ? View.GONE : View.VISIBLE);

    updateButtons();
}