Java Code Examples for java.util.concurrent.ScheduledThreadPoolExecutor#shutdown()

The following examples show how to use java.util.concurrent.ScheduledThreadPoolExecutor#shutdown() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ZeroCorePoolSize.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
void test(String[] args) throws Throwable {

        ScheduledThreadPoolExecutor pool = new ScheduledThreadPoolExecutor(0);
        Runnable task = new Runnable() {
            public void run() {
                taskRun = true;
            }
        };
        check(pool.getCorePoolSize() == 0);

        pool.schedule(task, 1, TimeUnit.SECONDS);

        pool.shutdown();
        check(pool.awaitTermination(20L, TimeUnit.SECONDS));
        check(pool.getCorePoolSize() == 0);
        check(taskRun);
    }
 
Example 2
Source File: ZeroCorePoolSize.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
void test(String[] args) throws Throwable {

        ScheduledThreadPoolExecutor pool = new ScheduledThreadPoolExecutor(0);
        Runnable task = new Runnable() {
            public void run() {
                taskRun = true;
            }
        };
        check(pool.getCorePoolSize() == 0);

        pool.schedule(task, 1, TimeUnit.SECONDS);

        pool.shutdown();
        check(pool.awaitTermination(20L, TimeUnit.SECONDS));
        check(pool.getCorePoolSize() == 0);
        check(taskRun);
    }
 
Example 3
Source File: BasicCancelTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
void test(String[] args) throws Throwable {

        final ScheduledThreadPoolExecutor pool =
            new ScheduledThreadPoolExecutor(1);

        // Needed to avoid OOME
        pool.setRemoveOnCancelPolicy(true);

        final long moreThanYouCanChew = Runtime.getRuntime().freeMemory() / 4;
        System.out.printf("moreThanYouCanChew=%d%n", moreThanYouCanChew);

        Runnable noopTask = new Runnable() { public void run() {}};

        for (long i = 0; i < moreThanYouCanChew; i++)
            pool.schedule(noopTask, 10, TimeUnit.MINUTES).cancel(true);

        pool.shutdown();
        check(pool.awaitTermination(1L, TimeUnit.DAYS));
        checkTerminated(pool);
        equal(pool.getTaskCount(), 0L);
        equal(pool.getCompletedTaskCount(), 0L);
    }
 
Example 4
Source File: ZeroCorePoolSize.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
void test(String[] args) throws Throwable {

        ScheduledThreadPoolExecutor pool = new ScheduledThreadPoolExecutor(0);
        Runnable task = new Runnable() {
            public void run() {
                taskRun = true;
            }
        };
        check(pool.getCorePoolSize() == 0);

        pool.schedule(task, 1, TimeUnit.SECONDS);

        pool.shutdown();
        check(pool.awaitTermination(20L, TimeUnit.SECONDS));
        check(pool.getCorePoolSize() == 0);
        check(taskRun);
    }
 
Example 5
Source File: ZeroCorePoolSize.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
void test(String[] args) throws Throwable {

        ScheduledThreadPoolExecutor pool = new ScheduledThreadPoolExecutor(0);
        Runnable task = new Runnable() {
            public void run() {
                taskRun = true;
            }
        };
        check(pool.getCorePoolSize() == 0);

        pool.schedule(task, 1, TimeUnit.SECONDS);

        pool.shutdown();
        check(pool.awaitTermination(20L, TimeUnit.SECONDS));
        check(pool.getCorePoolSize() == 0);
        check(taskRun);
    }
 
Example 6
Source File: ZeroCorePoolSize.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
void test(String[] args) throws Throwable {

        ScheduledThreadPoolExecutor pool = new ScheduledThreadPoolExecutor(0);
        Runnable task = new Runnable() {
            public void run() {
                taskRun = true;
            }
        };
        check(pool.getCorePoolSize() == 0);

        pool.schedule(task, 1, TimeUnit.SECONDS);

        pool.shutdown();
        check(pool.awaitTermination(20L, TimeUnit.SECONDS));
        check(pool.getCorePoolSize() == 0);
        check(taskRun);
    }
 
Example 7
Source File: ZeroCorePoolSize.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
void test(String[] args) throws Throwable {

        ScheduledThreadPoolExecutor pool = new ScheduledThreadPoolExecutor(0);
        Runnable task = new Runnable() {
            public void run() {
                taskRun = true;
            }
        };
        check(pool.getCorePoolSize() == 0);

        pool.schedule(task, 1, TimeUnit.SECONDS);

        pool.shutdown();
        check(pool.awaitTermination(20L, TimeUnit.SECONDS));
        check(pool.getCorePoolSize() == 0);
        check(taskRun);
    }
 
Example 8
Source File: ZeroCorePoolSize.java    From native-obfuscator with GNU General Public License v3.0 6 votes vote down vote up
void test(String[] args) throws Throwable {

        ScheduledThreadPoolExecutor pool = new ScheduledThreadPoolExecutor(0);
        Runnable task = new Runnable() {
            public void run() {
                taskRun = true;
            }
        };
        check(pool.getCorePoolSize() == 0);

        pool.schedule(task, 1, TimeUnit.SECONDS);

        pool.shutdown();
        check(pool.awaitTermination(20L, TimeUnit.SECONDS));
        check(pool.getCorePoolSize() == 0);
        check(taskRun);
    }
 
Example 9
Source File: ZeroCorePoolSize.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
void test(String[] args) throws Throwable {

        ScheduledThreadPoolExecutor pool = new ScheduledThreadPoolExecutor(0);
        Runnable task = new Runnable() {
            public void run() {
                taskRun = true;
            }
        };
        check(pool.getCorePoolSize() == 0);

        pool.schedule(task, 1, TimeUnit.SECONDS);

        pool.shutdown();
        check(pool.awaitTermination(20L, TimeUnit.SECONDS));
        check(pool.getCorePoolSize() == 0);
        check(taskRun);
    }
 
Example 10
Source File: ContextTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void cancellationCancelsScheduledTask() {
  ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
  try {
    assertEquals(0, executor.getQueue().size());
    Context.CancellableContext base
        = Context.current().withDeadline(Deadline.after(1, TimeUnit.DAYS), executor);
    assertEquals(1, executor.getQueue().size());
    base.cancel(null);
    executor.purge();
    assertEquals(0, executor.getQueue().size());
  } finally {
    executor.shutdown();
  }
}
 
Example 11
Source File: ContextTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void cancellationCancelsScheduledTask() {
  ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
  try {
    assertEquals(0, executor.getQueue().size());
    Context.CancellableContext base
        = Context.current().withDeadline(Deadline.after(1, TimeUnit.DAYS), executor);
    assertEquals(1, executor.getQueue().size());
    base.cancel(null);
    executor.purge();
    assertEquals(0, executor.getQueue().size());
  } finally {
    executor.shutdown();
  }
}
 
Example 12
Source File: ScheduledExecutorTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * scheduleAtFixedRate throws RejectedExecutionException if shutdown
 */
public void testScheduleAtFixedRate1_RejectedExecutionException() throws InterruptedException {
    final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
    try (PoolCleaner cleaner = cleaner(p)) {
        try {
            p.shutdown();
            p.scheduleAtFixedRate(new NoOpRunnable(),
                                  MEDIUM_DELAY_MS, MEDIUM_DELAY_MS, MILLISECONDS);
            shouldThrow();
        } catch (RejectedExecutionException success) {
        } catch (SecurityException ok) {}
    }
}
 
Example 13
Source File: TestNonBlockingReads.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 100000)
public void testNonBlockingRead() throws Exception {
    String name = "distrlog-non-blocking-reader";
    final DistributedLogConfiguration confLocal = new DistributedLogConfiguration();
    confLocal.loadConf(conf);
    confLocal.setReadAheadBatchSize(1);
    confLocal.setReadAheadMaxRecords(1);
    confLocal.setReaderIdleWarnThresholdMillis(100);
    confLocal.setReadLACLongPollTimeout(49);
    final DistributedLogManager dlm = createNewDLM(confLocal, name);
    ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
    ScheduledFuture writerClosedFuture = null;
    try {
        final Thread currentThread = Thread.currentThread();
        writerClosedFuture = executor.schedule(
                new Runnable() {
                    @Override
                    public void run() {
                        try {
                            writeRecordsForNonBlockingReads(confLocal, dlm, false);
                        } catch (Exception exc) {
                            currentThread.interrupt();
                        }

                    }
                }, 100, TimeUnit.MILLISECONDS);

        readNonBlocking(dlm, false);
        assertFalse(currentThread.isInterrupted());
    } finally {
        if (writerClosedFuture != null){
            // ensure writer.closeAndComplete is done before we close dlm
            writerClosedFuture.get();
        }
        executor.shutdown();
        dlm.close();
    }
}
 
Example 14
Source File: ScheduledExecutorTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * schedule callable throws RejectedExecutionException if shutdown
 */
public void testSchedule3_RejectedExecutionException() throws InterruptedException {
    final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
    try (PoolCleaner cleaner = cleaner(p)) {
        try {
            p.shutdown();
            p.schedule(new NoOpCallable(),
                       MEDIUM_DELAY_MS, MILLISECONDS);
            shouldThrow();
        } catch (RejectedExecutionException success) {
        } catch (SecurityException ok) {}
    }
}
 
Example 15
Source File: TestNonBlockingReads.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 100000)
public void testNonBlockingReadRecovery() throws Exception {
    String name = "distrlog-non-blocking-reader-recovery";
    final DistributedLogConfiguration confLocal = new DistributedLogConfiguration();
    confLocal.loadConf(conf);
    confLocal.setReadAheadBatchSize(10);
    confLocal.setReadAheadMaxRecords(10);
    final DistributedLogManager dlm = createNewDLM(confLocal, name);
    ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
    ScheduledFuture writerClosedFuture = null;
    try {
        final Thread currentThread = Thread.currentThread();
        writerClosedFuture = executor.schedule(
                new Runnable() {
                    @Override
                    public void run() {
                        try {
                            writeRecordsForNonBlockingReads(confLocal, dlm, true);
                        } catch (Exception exc) {
                            currentThread.interrupt();
                        }

                    }
                }, 100, TimeUnit.MILLISECONDS);


        readNonBlocking(dlm, false);
        assertFalse(currentThread.isInterrupted());
    } finally {
        if (writerClosedFuture != null){
            // ensure writer.closeAndComplete is done before we close dlm
            writerClosedFuture.get();
        }
        executor.shutdown();
        dlm.close();
    }
}
 
Example 16
Source File: Scheduler.java    From crate with Apache License 2.0 5 votes vote down vote up
static boolean terminate(ScheduledThreadPoolExecutor scheduledThreadPoolExecutor, long timeout, TimeUnit timeUnit) {
    scheduledThreadPoolExecutor.shutdown();
    if (awaitTermination(scheduledThreadPoolExecutor, timeout, timeUnit)) {
        return true;
    }
    // last resort
    scheduledThreadPoolExecutor.shutdownNow();
    return awaitTermination(scheduledThreadPoolExecutor, timeout, timeUnit);
}
 
Example 17
Source File: ServiceBackgroundTaskManager.java    From sepia-assist-server with MIT License 4 votes vote down vote up
/**
 * Run a given task in background and manage task references and threads.
 * @param userId
 * @param serviceId
 * @param delayMs
 * @param task
 * @return
 */
public static ServiceBackgroundTask runOnceInBackground(String userId, String serviceId, long delayMs, Runnable task){
	//TODO: introduce max. delay ?
	String taskId = getNewTaskId();
	
	int corePoolSize = 1;
    final ScheduledThreadPoolExecutor executor = ThreadManager.getNewScheduledThreadPool(corePoolSize);
    executor.setRemoveOnCancelPolicy(true);
    ScheduledFuture<?> future = executor.schedule(() -> {
    	//run task and...
    	try{
    		increaseThreadCounter();
    		task.run();
    		decreaseThreadCounter();
    	}catch (Exception e){
    		decreaseThreadCounter();
		}
    	//... remove yourself from manager
    	removeFromSbtMap(taskId);
    	executor.purge();
    	executor.shutdown();
    	
    }, delayMs, TimeUnit.MILLISECONDS);
    //other option (but does not support lambda expression):
    //Timer timer = new Timer();
    //timer.schedule(task, delayMs);
    
    BooleanSupplier cancelFun = () -> {
    	if (future.isDone() || future.cancel(false)){
    		removeFromSbtMap(taskId);
    		executor.purge();
	    	executor.shutdown();
    		return true;
    	}else{
    		executor.purge();
	    	executor.shutdown();
    		return false;
    	}
    };
    
    ServiceBackgroundTask sbt = new ServiceBackgroundTask(serviceId, taskId, future, cancelFun);
    addToSbtMap(taskId, sbt);
    return sbt;
}
 
Example 18
Source File: ReferenceQueueTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
private void runLater(Runnable runnable, int delayMillis) {
    ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
    executor.schedule(runnable, delayMillis, TimeUnit.MILLISECONDS);
    executor.shutdown();
}
 
Example 19
Source File: HeartbeatManagerTest.java    From flink with Apache License 2.0 4 votes vote down vote up
/**
 * Tests that the heartbeat target {@link ResourceID} is properly passed to the {@link HeartbeatListener} by the
 * {@link HeartbeatManagerSenderImpl}.
 */
@Test
public void testHeartbeatManagerSenderTargetPayload() throws Exception {
	final long heartbeatTimeout = 100L;
	final long heartbeatPeriod = 2000L;

	final ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(1);

	final ResourceID someTargetId = ResourceID.generate();
	final ResourceID specialTargetId = ResourceID.generate();

	final OneShotLatch someTargetReceivedLatch = new OneShotLatch();
	final OneShotLatch specialTargetReceivedLatch = new OneShotLatch();

	final TargetDependentHeartbeatReceiver someHeartbeatTarget = new TargetDependentHeartbeatReceiver(someTargetReceivedLatch);
	final TargetDependentHeartbeatReceiver specialHeartbeatTarget = new TargetDependentHeartbeatReceiver(specialTargetReceivedLatch);

	final int defaultResponse = 0;
	final int specialResponse = 1;

	HeartbeatManager<?, Integer> heartbeatManager = new HeartbeatManagerSenderImpl<>(
		heartbeatPeriod,
		heartbeatTimeout,
		ResourceID.generate(),
		new TargetDependentHeartbeatSender(specialTargetId, specialResponse, defaultResponse),
		new ScheduledExecutorServiceAdapter(scheduledThreadPoolExecutor),
		LOG);

	try {
		heartbeatManager.monitorTarget(someTargetId, someHeartbeatTarget);
		heartbeatManager.monitorTarget(specialTargetId, specialHeartbeatTarget);

		someTargetReceivedLatch.await(5, TimeUnit.SECONDS);
		specialTargetReceivedLatch.await(5, TimeUnit.SECONDS);

		assertEquals(defaultResponse, someHeartbeatTarget.getLastRequestedHeartbeatPayload());
		assertEquals(specialResponse, specialHeartbeatTarget.getLastRequestedHeartbeatPayload());
	} finally {
		heartbeatManager.stop();
		scheduledThreadPoolExecutor.shutdown();
	}
}
 
Example 20
Source File: HeartbeatManagerTest.java    From Flink-CEPplus with Apache License 2.0 4 votes vote down vote up
/**
 * Tests that the heartbeat target {@link ResourceID} is properly passed to the {@link HeartbeatListener} by the
 * {@link HeartbeatManagerSenderImpl}.
 */
@Test
public void testHeartbeatManagerSenderTargetPayload() throws Exception {
	final long heartbeatTimeout = 100L;
	final long heartbeatPeriod = 2000L;

	final ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(1);

	final ResourceID someTargetId = ResourceID.generate();
	final ResourceID specialTargetId = ResourceID.generate();

	final OneShotLatch someTargetReceivedLatch = new OneShotLatch();
	final OneShotLatch specialTargetReceivedLatch = new OneShotLatch();

	final TargetDependentHeartbeatReceiver someHeartbeatTarget = new TargetDependentHeartbeatReceiver(someTargetReceivedLatch);
	final TargetDependentHeartbeatReceiver specialHeartbeatTarget = new TargetDependentHeartbeatReceiver(specialTargetReceivedLatch);

	final int defaultResponse = 0;
	final int specialResponse = 1;

	HeartbeatManager<?, Integer> heartbeatManager = new HeartbeatManagerSenderImpl<>(
		heartbeatPeriod,
		heartbeatTimeout,
		ResourceID.generate(),
		new TargetDependentHeartbeatSender(specialTargetId, specialResponse, defaultResponse),
		new ScheduledExecutorServiceAdapter(scheduledThreadPoolExecutor),
		LOG);

	try {
		heartbeatManager.monitorTarget(someTargetId, someHeartbeatTarget);
		heartbeatManager.monitorTarget(specialTargetId, specialHeartbeatTarget);

		someTargetReceivedLatch.await(5, TimeUnit.SECONDS);
		specialTargetReceivedLatch.await(5, TimeUnit.SECONDS);

		assertEquals(defaultResponse, someHeartbeatTarget.getLastRequestedHeartbeatPayload());
		assertEquals(specialResponse, specialHeartbeatTarget.getLastRequestedHeartbeatPayload());
	} finally {
		heartbeatManager.stop();
		scheduledThreadPoolExecutor.shutdown();
	}
}