Example #1
0
        public void ExecuteRunsTaskInCurrentThreadWhenSaturatedWithCallerRunsPolicy()
        {
            IRejectedExecutionHandler h = new ThreadPoolExecutor.CallerRunsPolicy();
            var es = new ThreadPoolExecutor(1, 1, Delays.Long, new ArrayBlockingQueue <IRunnable>(1), h);

            ExecutorService = es;
            IRunnable[] tasks  = new IRunnable[_size];
            var         caller = Thread.CurrentThread;

            for (int i = 0; i < _size; ++i)
            {
                tasks[i] = MockRepository.GenerateStub <IRunnable>();
                tasks[i].Stub(r => r.Run()).Do(
                    ThreadManager.GetManagedAction(
                        () => Assert.That(Thread.CurrentThread, Is.EqualTo(caller))));
            }

            es.Execute(_mediumInterruptableAction);
            for (int i = 0; i < _size; ++i)
            {
                es.Execute(tasks[i]);
            }

            for (int i = 1; i < _size; ++i)
            {
                tasks[i].AssertWasCalled(r => r.Run());
            }
            InterruptAndJoinPool(es);
            ThreadManager.JoinAndVerify();
        }
Example #2
0
        public void ExecuteDropsTaskWhenSaturatedWithDiscardPolicy()
        {
            IRejectedExecutionHandler h = new ThreadPoolExecutor.DiscardPolicy();
            var es = new ThreadPoolExecutor(1, 1, Delays.Long, new ArrayBlockingQueue <IRunnable>(1), h);

            ExecutorService = es;
            IRunnable[] tasks = new IRunnable[_size];
            for (int i = 0; i < _size; ++i)
            {
                tasks[i] = MockRepository.GenerateStub <IRunnable>();
            }

            es.Execute(_mediumInterruptableAction);
            for (int i = 0; i < _size; ++i)
            {
                es.Execute(tasks[i]);
            }

            for (int i = 1; i < _size; ++i)
            {
                tasks[i].AssertWasNotCalled(r => r.Run());
            }
            InterruptAndJoinPool(es);
            ThreadManager.JoinAndVerify();
        }
Example #3
0
        public void ExecuteAllowsResubmitSameTask()
        {
            const int     nTasks   = 1000;
            AtomicInteger nRun     = new AtomicInteger(0);
            IRunnable     runnable = new Runnable(() => nRun.IncrementValueAndReturn());
            var           es       = new ThreadPoolExecutor(1, 30, Delays.Long, new ArrayBlockingQueue <IRunnable>(30));

            ExecutorService = es;
            for (int i = 0; i < nTasks; ++i)
            {
                for (; ;)
                {
                    try
                    {
                        es.Execute(runnable);
                        break;
                    }
                    catch (RejectedExecutionException)
                    {
                    }
                }
            }
            // enough time to run all tasks
            for (int i = 0; i < 20 && nRun.Value < nTasks; i++)
            {
                Thread.Sleep(Delays.Short);
            }
            Assert.AreEqual(nRun.Value, nTasks);
        }
Example #4
0
        public void ExecutionContinuesWithOneThreadWhenFactoryFailesToCreateMore()
        {
            var       nRun   = new AtomicInteger(0);
            const int nTasks = 100;

            var failingThreadFactory = MockRepository.GenerateStub <IThreadFactory>();

            failingThreadFactory.Stub(f => f.NewThread(Arg <IRunnable> .Is.NotNull))
            .Do(new Function <IRunnable, Thread>(r => new Thread(r.Run))).Repeat.Once();

            var es = new ThreadPoolExecutor(nTasks, nTasks, Delays.Long,
                                            new LinkedBlockingQueue <IRunnable>(), failingThreadFactory);

            ExecutorService = es;

            for (int k = 0; k < nTasks; ++k)
            {
                es.Execute(() => nRun.IncrementValueAndReturn());
            }
            for (int i = 0; i < 20 && nRun.Value < nTasks; i++)
            {
                Thread.Sleep(Delays.Short);
            }
            Assert.That(es.PoolSize, Is.EqualTo(1));
            Assert.AreEqual(nTasks, nRun.Value);
        }
Example #5
0
 public void Execute(IMailbox mailbox)
 {
     if (!IsClosed)
     {
         _executor.Execute(mailbox);
     }
 }
 /// <summary> 
 /// Obtains and ignores the next task that the <paramref name="executor"/>
 /// would otherwise execute, if one is immediately available,
 /// and then retries execution of task <paramref name="runnable"/>, unless the <paramref name="executor"/>
 /// is shut down, in which case task <paramref name="runnable"/> is instead discarded.
 /// </summary>
 /// <param name="runnable">the <see cref="Spring.Threading.IRunnable"/> task requested to be executed</param>
 /// <param name="executor">the <see cref="Spring.Threading.Execution.ThreadPoolExecutor"/> attempting to execute this task</param>
 public virtual void RejectedExecution(IRunnable runnable, ThreadPoolExecutor executor)
 {
     if (executor.IsShutdown) return;
     IRunnable head;
     executor.Queue.Poll(out head);
     executor.Execute(runnable);
 }
        public void ExecuteTest()
        {
            ThreadPoolExecutor executor = new ThreadPoolExecutor(10, Executors.DefaultThreadFactory());

            executor.Execute(new RunnableAction(delegate {
                Console.WriteLine("Yarrrrr!");
            }));
        }
Example #8
0
        internal virtual void UncacheBlock(string bpid, long blockId)
        {
            lock (this)
            {
                ExtendedBlockId      key       = new ExtendedBlockId(blockId, bpid);
                FsDatasetCache.Value prevValue = mappableBlockMap[key];
                bool deferred = false;
                if (!dataset.datanode.GetShortCircuitRegistry().ProcessBlockMunlockRequest(key))
                {
                    deferred = true;
                }
                if (prevValue == null)
                {
                    Log.Debug("Block with id {}, pool {} does not need to be uncached, " + "because it is not currently in the mappableBlockMap."
                              , blockId, bpid);
                    numBlocksFailedToUncache.IncrementAndGet();
                    return;
                }
                switch (prevValue.state)
                {
                case FsDatasetCache.State.Caching:
                {
                    Log.Debug("Cancelling caching for block with id {}, pool {}.", blockId, bpid);
                    mappableBlockMap[key] = new FsDatasetCache.Value(prevValue.mappableBlock, FsDatasetCache.State
                                                                     .CachingCancelled);
                    break;
                }

                case FsDatasetCache.State.Cached:
                {
                    mappableBlockMap[key] = new FsDatasetCache.Value(prevValue.mappableBlock, FsDatasetCache.State
                                                                     .Uncaching);
                    if (deferred)
                    {
                        Log.Debug("{} is anchored, and can't be uncached now.  Scheduling it " + "for uncaching in {} "
                                  , key, DurationFormatUtils.FormatDurationHMS(revocationPollingMs));
                        deferredUncachingExecutor.Schedule(new FsDatasetCache.UncachingTask(this, key, revocationMs
                                                                                            ), revocationPollingMs, TimeUnit.Milliseconds);
                    }
                    else
                    {
                        Log.Debug("{} has been scheduled for immediate uncaching.", key);
                        uncachingExecutor.Execute(new FsDatasetCache.UncachingTask(this, key, 0));
                    }
                    break;
                }

                default:
                {
                    Log.Debug("Block with id {}, pool {} does not need to be uncached, " + "because it is in state {}."
                              , blockId, bpid, prevValue.state);
                    numBlocksFailedToUncache.IncrementAndGet();
                    break;
                }
                }
            }
        }
Example #9
0
        public void ExecuteDropsOldestTaskWhenSaturatedWithDiscardOldestPolicy()
        {
            IRejectedExecutionHandler h = new ThreadPoolExecutor.DiscardOldestPolicy();
            var es = new ThreadPoolExecutor(1, 1, Delays.Long, new ArrayBlockingQueue <IRunnable>(1), h);

            ExecutorService = es;
            es.Execute(_mediumInterruptableAction);
            var r2 = MockRepository.GenerateStub <IRunnable>();

            es.Execute(r2);
            Assert.IsTrue(es.Queue.Contains(r2));
            var r3 = MockRepository.GenerateStub <IRunnable>();

            es.Execute(r3);
            Assert.IsFalse(es.Queue.Contains(r2));
            Assert.IsTrue(es.Queue.Contains(r3));
            InterruptAndJoinPool(es);
        }
 protected internal virtual void ScheduleNext()
 {
     lock (this)
     {
         if ((mActive = mTasks.Poll()) != null)
         {
             ThreadPoolExecutor.Execute(mActive);
         }
     }
 }
Example #11
0
        /// <summary>
        /// Obtains and ignores the next task that the <paramref name="executor"/>
        /// would otherwise execute, if one is immediately available,
        /// and then retries execution of task <paramref name="runnable"/>, unless the <paramref name="executor"/>
        /// is shut down, in which case task <paramref name="runnable"/> is instead discarded.
        /// </summary>
        /// <param name="runnable">the <see cref="Spring.Threading.IRunnable"/> task requested to be executed</param>
        /// <param name="executor">the <see cref="Spring.Threading.Execution.ThreadPoolExecutor"/> attempting to execute this task</param>
        public virtual void RejectedExecution(IRunnable runnable, ThreadPoolExecutor executor)
        {
            if (executor.IsShutdown)
            {
                return;
            }
            IRunnable head;

            executor.Queue.Poll(out head);
            executor.Execute(runnable);
        }
Example #12
0
 /// <summary>Execute the task sometime in the future, using ThreadPools.</summary>
 public virtual void Execute(string root, Runnable task)
 {
     lock (this)
     {
         ThreadPoolExecutor executor = executors[root];
         if (executor == null)
         {
             throw new RuntimeException("Cannot find root " + root + " for execution of task "
                                        + task);
         }
         else
         {
             executor.Execute(task);
         }
     }
 }
Example #13
0
        public void AllowsCoreThreadTimeOutControlsIdleThreadTimeout([Values(true, false)] bool isTimeout)
        {
            var es = new ThreadPoolExecutor(2, 10, TimeSpan.FromMilliseconds(10), new ArrayBlockingQueue <IRunnable>(10));

            ExecutorService = es;
            es.AllowsCoreThreadsToTimeOut = isTimeout;
            es.Execute(ThreadManager.GetManagedAction(() => { }));
            Thread.Sleep(Delays.Short);
            if (isTimeout)
            {
                Assert.That(es.PoolSize, Is.EqualTo(0));
            }
            else
            {
                Assert.That(es.PoolSize, Is.GreaterThan(0));
            }
        }
 /// <summary>Execute the task sometime in the future, using ThreadPools.</summary>
 internal virtual void Execute(FilePath root, Runnable task)
 {
     lock (this)
     {
         if (executors == null)
         {
             throw new RuntimeException("AsyncLazyPersistService is already shutdown");
         }
         ThreadPoolExecutor executor = executors[root];
         if (executor == null)
         {
             throw new RuntimeException("Cannot find root " + root + " for execution of task "
                                        + task);
         }
         else
         {
             executor.Execute(task);
         }
     }
 }
Example #15
0
        public void QueueRetursWorkQueuContainsQueuedTasks()
        {
            IBlockingQueue <IRunnable> q = new ArrayBlockingQueue <IRunnable>(10);
            var es = new ThreadPoolExecutor(1, 1, Delays.Long, q);

            ExecutorService = es;
            FutureTask <bool>[] tasks = new FutureTask <bool> [_size];
            for (int i = 0; i < _size; i++)
            {
                tasks[i] = new FutureTask <bool>(_mediumInterruptableAction, true);
                es.Execute(tasks[i]);
            }
            Thread.Sleep(Delays.Short);
            IBlockingQueue <IRunnable> wq = es.Queue;

            Assert.AreEqual(q, wq);
            Assert.IsFalse(wq.Contains(tasks[0]));
            Assert.IsTrue(wq.Contains(tasks[_size - 1]));
            for (int i = 1; i < _size; ++i)
            {
                tasks[i].Cancel(true);
            }
        }
Example #16
0
        public void RemoveRunnableRemovesQueuedTaskAndFailesToRemoveActiveTask()
        {
            IBlockingQueue <IRunnable> q = new ArrayBlockingQueue <IRunnable>(10);
            var es = new ThreadPoolExecutor(1, 1, Delays.Long, q);

            ExecutorService = es;
            FutureTask <bool>[] tasks = new FutureTask <bool> [5];
            for (int i = 0; i < 5; i++)
            {
                tasks[i] = new FutureTask <bool>(_mediumInterruptableAction, true);
                es.Execute(tasks[i]);
            }
            Thread.Sleep(Delays.Short);
            Assert.IsFalse(es.Remove(tasks[0]));
            Assert.IsTrue(q.Contains(tasks[4]));
            Assert.IsTrue(q.Contains(tasks[3]));
            Assert.IsTrue(es.Remove(tasks[4]));
            Assert.IsFalse(es.Remove(tasks[4]));
            Assert.IsFalse(q.Contains(tasks[4]));
            Assert.IsTrue(q.Contains(tasks[3]));
            Assert.IsTrue(es.Remove(tasks[3]));
            Assert.IsFalse(q.Contains(tasks[3]));
            InterruptAndJoinPool(es);
        }
Example #17
0
        public void RemoveActionRemovesQueuedTaskAndFailesToRemoveActiveTask()
        {
            IBlockingQueue <IRunnable> q = new ArrayBlockingQueue <IRunnable>(10);
            var es = new ThreadPoolExecutor(1, 1, Delays.Long, q);

            ExecutorService = es;
            var tasks = new Action[5];

            for (int i = 0; i < 5; i++)
            {
                int timeout = i;
                tasks[i] = NewInterruptableAction(Delays.Medium + TimeSpan.FromMilliseconds(timeout));
                es.Execute(tasks[i]);
            }
            Thread.Sleep(Delays.Short);
            Assert.IsFalse(es.Remove(tasks[0]));
            Assert.That(q.Count, Is.EqualTo(4));
            Assert.IsTrue(es.Remove(tasks[4]));
            Assert.IsFalse(es.Remove(tasks[4]));
            Assert.That(q.Count, Is.EqualTo(3));
            Assert.IsTrue(es.Remove(tasks[3]));
            Assert.That(q.Count, Is.EqualTo(2));
            InterruptAndJoinPool(es);
        }
Example #18
0
 public void QueueUserWorkItem(WaitCallback callBack)
 {
     _threadPool.Execute(() => callBack(null));
 }