scheduledexecutortest.java

来自「SRI international 发布的OAA框架软件」· Java 代码 · 共 1,149 行 · 第 1/3 页

JAVA
1,149
字号
    public void testGetThreadFactory() {
        ThreadFactory tf = new SimpleThreadFactory();
	ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1, tf);
        assertSame(tf, p.getThreadFactory());
        joinPool(p);
    }

    /**
     * setThreadFactory sets the thread factory returned by getThreadFactory
     */
    public void testSetThreadFactory() {
        ThreadFactory tf = new SimpleThreadFactory();
	ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
        p.setThreadFactory(tf);
        assertSame(tf, p.getThreadFactory());
        joinPool(p);
    }

    /**
     * setThreadFactory(null) throws NPE
     */
    public void testSetThreadFactoryNull() {
	ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
        try {
            p.setThreadFactory(null);
            shouldThrow();
        } catch (NullPointerException success) {
        } finally {
            joinPool(p);
        }
    }

    /**
     *   is isShutDown is false before shutdown, true after
     */
    public void testIsShutdown() {

	ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
        try {
            assertFalse(p1.isShutdown());
        }
        finally {
            try { p1.shutdown(); } catch(SecurityException ok) { return; }
        }
	assertTrue(p1.isShutdown());
    }


    /**
     *   isTerminated is false before termination, true after
     */
    public void testIsTerminated() {
	ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
        try {
            p1.execute(new SmallRunnable());
        } finally {
            try { p1.shutdown(); } catch(SecurityException ok) { return; }
        }
        try {
	    assertTrue(p1.awaitTermination(LONG_DELAY_MS, TimeUnit.MILLISECONDS));
            assertTrue(p1.isTerminated());
	} catch(Exception e){
            unexpectedException();
        }
    }

    /**
     *  isTerminating is not true when running or when terminated
     */
    public void testIsTerminating() {
	ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
        assertFalse(p1.isTerminating());
        try {
            p1.execute(new SmallRunnable());
            assertFalse(p1.isTerminating());
        } finally {
            try { p1.shutdown(); } catch(SecurityException ok) { return; }
        }
        try {
	    assertTrue(p1.awaitTermination(LONG_DELAY_MS, TimeUnit.MILLISECONDS));
            assertTrue(p1.isTerminated());
            assertFalse(p1.isTerminating());
	} catch(Exception e){
            unexpectedException();
        }
    }

    /**
     * getQueue returns the work queue, which contains queued tasks
     */
    public void testGetQueue() {
        ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
        ScheduledFuture[] tasks = new ScheduledFuture[5];
        for(int i = 0; i < 5; i++){
            tasks[i] = p1.schedule(new SmallPossiblyInterruptedRunnable(), 1, TimeUnit.MILLISECONDS);
        }
        try {
            Thread.sleep(SHORT_DELAY_MS);
            BlockingQueue q = p1.getQueue();
            assertTrue(q.contains(tasks[4]));
            assertFalse(q.contains(tasks[0]));
        } catch(Exception e) {
            unexpectedException();
        } finally {
            joinPool(p1);
        }
    }

    /**
     * remove(task) removes queued task, and fails to remove active task
     */
    public void testRemove() {
        ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
        ScheduledFuture[] tasks = new ScheduledFuture[5];
        for(int i = 0; i < 5; i++){
            tasks[i] = p1.schedule(new SmallPossiblyInterruptedRunnable(), 1, TimeUnit.MILLISECONDS);
        }
        try {
            Thread.sleep(SHORT_DELAY_MS);
            BlockingQueue q = p1.getQueue();
            assertFalse(p1.remove((Runnable)tasks[0]));
            assertTrue(q.contains((Runnable)tasks[4]));
            assertTrue(q.contains((Runnable)tasks[3]));
            assertTrue(p1.remove((Runnable)tasks[4]));
            assertFalse(p1.remove((Runnable)tasks[4]));
            assertFalse(q.contains((Runnable)tasks[4]));
            assertTrue(q.contains((Runnable)tasks[3]));
            assertTrue(p1.remove((Runnable)tasks[3]));
            assertFalse(q.contains((Runnable)tasks[3]));
        } catch(Exception e) {
            unexpectedException();
        } finally {
            joinPool(p1);
        }
    }

    /**
     *  purge removes cancelled tasks from the queue
     */
    public void testPurge() {
        ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
        ScheduledFuture[] tasks = new ScheduledFuture[5];
        for(int i = 0; i < 5; i++){
            tasks[i] = p1.schedule(new SmallPossiblyInterruptedRunnable(), SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
        }
        try {
            int max = 5;
            if (tasks[4].cancel(true)) --max;
            if (tasks[3].cancel(true)) --max;
            // There must eventually be an interference-free point at
            // which purge will not fail. (At worst, when queue is empty.)
            int k;
            for (k = 0; k < SMALL_DELAY_MS; ++k) {
                p1.purge();
                long count = p1.getTaskCount();
                if (count >= 0 && count <= max)
                    break;
                Thread.sleep(1);
            }
            assertTrue(k < SMALL_DELAY_MS);
        } catch(Exception e) {
            unexpectedException();
        } finally {
            joinPool(p1);
        }
    }

    /**
     *  shutDownNow returns a list containing tasks that were not run
     */
    public void testShutDownNow() {
	ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
        for(int i = 0; i < 5; i++)
            p1.schedule(new SmallPossiblyInterruptedRunnable(), SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
        List l;
        try {
            l = p1.shutdownNow();
        } catch (SecurityException ok) {
            return;
        }
	assertTrue(p1.isShutdown());
	assertTrue(l.size() > 0 && l.size() <= 5);
        joinPool(p1);
    }

    /**
     * In default setting, shutdown cancels periodic but not delayed
     * tasks at shutdown
     */
    public void testShutDown1() {
        try {
            ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
            assertTrue(p1.getExecuteExistingDelayedTasksAfterShutdownPolicy());
            assertFalse(p1.getContinueExistingPeriodicTasksAfterShutdownPolicy());

            ScheduledFuture[] tasks = new ScheduledFuture[5];
            for(int i = 0; i < 5; i++)
                tasks[i] = p1.schedule(new NoOpRunnable(), SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
            try { p1.shutdown(); } catch(SecurityException ok) { return; }
            BlockingQueue q = p1.getQueue();
            for (Iterator it = q.iterator(); it.hasNext();) {
                ScheduledFuture t = (ScheduledFuture)it.next();
                assertFalse(t.isCancelled());
            }
            assertTrue(p1.isShutdown());
            Thread.sleep(SMALL_DELAY_MS);
            for (int i = 0; i < 5; ++i) {
                assertTrue(tasks[i].isDone());
                assertFalse(tasks[i].isCancelled());
            }

        }
        catch(Exception ex) {
            unexpectedException();
        }
    }


    /**
     * If setExecuteExistingDelayedTasksAfterShutdownPolicy is false,
     * delayed tasks are cancelled at shutdown
     */
    public void testShutDown2() {
        try {
            ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
            p1.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
            ScheduledFuture[] tasks = new ScheduledFuture[5];
            for(int i = 0; i < 5; i++)
                tasks[i] = p1.schedule(new NoOpRunnable(), SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
            try { p1.shutdown(); } catch(SecurityException ok) { return; }
            assertTrue(p1.isShutdown());
            BlockingQueue q = p1.getQueue();
            assertTrue(q.isEmpty());
            Thread.sleep(SMALL_DELAY_MS);
            assertTrue(p1.isTerminated());
        }
        catch(Exception ex) {
            unexpectedException();
        }
    }


    /**
     * If setContinueExistingPeriodicTasksAfterShutdownPolicy is set false,
     * periodic tasks are not cancelled at shutdown
     */
    public void testShutDown3() {
        try {
            ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
            p1.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
            ScheduledFuture task =
                p1.scheduleAtFixedRate(new NoOpRunnable(), 5, 5, TimeUnit.MILLISECONDS);
            try { p1.shutdown(); } catch(SecurityException ok) { return; }
            assertTrue(p1.isShutdown());
            BlockingQueue q = p1.getQueue();
            assertTrue(q.isEmpty());
            Thread.sleep(SHORT_DELAY_MS);
            assertTrue(p1.isTerminated());
        }
        catch(Exception ex) {
            unexpectedException();
        }
    }

    /**
     * if setContinueExistingPeriodicTasksAfterShutdownPolicy is true,
     * periodic tasks are cancelled at shutdown
     */
    public void testShutDown4() {
        ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
        try {
            p1.setContinueExistingPeriodicTasksAfterShutdownPolicy(true);
            ScheduledFuture task =
                p1.scheduleAtFixedRate(new NoOpRunnable(), 1, 1, TimeUnit.MILLISECONDS);
            assertFalse(task.isCancelled());
            try { p1.shutdown(); } catch(SecurityException ok) { return; }
            assertFalse(task.isCancelled());
            assertFalse(p1.isTerminated());
            assertTrue(p1.isShutdown());
            Thread.sleep(SHORT_DELAY_MS);
            assertFalse(task.isCancelled());
            assertTrue(task.cancel(true));
            assertTrue(task.isDone());
            Thread.sleep(SHORT_DELAY_MS);
            assertTrue(p1.isTerminated());
        }
        catch(Exception ex) {
            unexpectedException();
        }
        finally {
            joinPool(p1);
        }
    }

    /**
     * completed submit of callable returns result
     */
    public void testSubmitCallable() {
        ExecutorService e = new ScheduledThreadPoolExecutor(2);
        try {
            Future future = e.submit(new StringTask());
            String result = (String)future.get();
            assertSame(TEST_STRING, result);
        }
        catch (ExecutionException ex) {
            unexpectedException();
        }
        catch (InterruptedException ex) {
            unexpectedException();
        } finally {
            joinPool(e);
        }
    }

    /**
     * completed submit of runnable returns successfully
     */
    public void testSubmitRunnable() {
        ExecutorService e = new ScheduledThreadPoolExecutor(2);
        try {
            Future future = e.submit(new NoOpRunnable());
            future.get();
            assertTrue(future.isDone());
        }
        catch (ExecutionException ex) {
            unexpectedException();
        }
        catch (InterruptedException ex) {
            unexpectedException();
        } finally {
            joinPool(e);
        }
    }

    /**
     * completed submit of (runnable, result) returns result
     */
    public void testSubmitRunnable2() {
        ExecutorService e = new ScheduledThreadPoolExecutor(2);
        try {
            Future future = e.submit(new NoOpRunnable(), TEST_STRING);
            String result = (String)future.get();
            assertSame(TEST_STRING, result);
        }
        catch (ExecutionException ex) {
            unexpectedException();
        }
        catch (InterruptedException ex) {
            unexpectedException();
        } finally {
            joinPool(e);
        }
    }

    /**
     * invokeAny(null) throws NPE
     */
    public void testInvokeAny1() {
        ExecutorService e = new ScheduledThreadPoolExecutor(2);
        try {
            e.invokeAny(null);
        } catch (NullPointerException success) {
        } catch(Exception ex) {
            unexpectedException();
        } finally {
            joinPool(e);
        }
    }

    /**
     * invokeAny(empty collection) throws IAE
     */
    public void testInvokeAny2() {
        ExecutorService e = new ScheduledThreadPoolExecutor(2);
        try {
            e.invokeAny(new ArrayList());
        } catch (IllegalArgumentException success) {
        } catch(Exception ex) {
            unexpectedException();
        } finally {
            joinPool(e);
        }
    }

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?