[Test] public void AwaitAfterMultipleReentrantLockingPreservesLockCount([Values(true, false)] bool isFair)
        {
            _lock = new ReentrantLock(isFair);
            ICondition c = _lock.NewCondition();

            ThreadManager.StartAndAssertRegistered(
                "T",
                delegate
            {
                using (_lock.Lock())
                {
                    Assert.That(_lock.HoldCount, Is.EqualTo(1));
                    c.Await();
                    Assert.That(_lock.HoldCount, Is.EqualTo(1));
                }
            },
                delegate
            {
                using (_lock.Lock())
                    using (_lock.Lock())
                    {
                        Assert.That(_lock.HoldCount, Is.EqualTo(2));
                        c.Await();
                        Assert.That(_lock.HoldCount, Is.EqualTo(2));
                    }
            });

            Thread.Sleep(Delays.Short);
            Assert.IsFalse(_lock.IsLocked);
            using (_lock.Lock()) c.SignalAll();

            ThreadManager.JoinAndVerify();
        }
        /// <summary>
        /// Retrieves and removes the head of this queue, waiting if necessary
        /// until an element becomes available.
        /// </summary>
        /// <returns> the head of this queue</returns>
        public override T Take()
        {
            ReentrantLock rl = _lock;

            rl.LockInterruptibly();
            try {
                try {
                    while (_innerQueue.Count == 0)
                    {
                        notEmpty.Await();
                    }
                }
                catch (ThreadInterruptedException) {
                    notEmpty.Signal(); // propagate to non-interrupted thread
                    throw;
                }
                T element;
                if (!_innerQueue.Poll(out element))
                {
                    throw new InvalidOperationException("Poll returns unexpected false");
                }
                return(element);
            }
            finally {
                rl.Unlock();
            }
        }
        public void GetWaitQueueLengthReturnsNumberOfThreads(bool isFair)
        {
            _lock = new ReentrantLock(isFair);

            ICondition c = _lock.NewCondition();

            ThreadManager.StartAndAssertRegistered(
                "T1",
                delegate
            {
                using (_lock.Lock())
                {
                    Assert.IsFalse(_lock.HasWaiters(c));
                    Assert.AreEqual(0, _lock.GetWaitQueueLength(c));
                    c.Await();
                }
            });

            Thread.Sleep(Delays.Short);
            ThreadManager.StartAndAssertRegistered(
                "T2",
                delegate
            {
                using (_lock.Lock())
                {
                    Assert.IsTrue(_lock.HasWaiters(c));
                    Assert.AreEqual(1, _lock.GetWaitQueueLength(c));
                    c.Await();
                }
            });
            try
            {
                Thread.Sleep(Delays.Short);
                _lock.Lock();
                Assert.IsTrue(_lock.HasWaiters(c));
                Assert.AreEqual(2, _lock.GetWaitQueueLength(c));
                c.SignalAll();
                _lock.Unlock();

                Thread.Sleep(Delays.Short);
                _lock.Lock();
                Assert.IsFalse(_lock.HasWaiters(c));
                Assert.AreEqual(0, _lock.GetWaitQueueLength(c));
                _lock.Unlock();
            }
            finally
            {
                ThreadManager.JoinAndVerify();
            }
        }
        [Test] public void HasWaitersReturnTrueWhenThreadIsWaitingElseFalse([Values(true, false)] bool isFair)
        {
            _lock = new ReentrantLock(true);
            ICondition c = _lock.NewCondition();

            ThreadManager.StartAndAssertRegistered(
                "T1",
                delegate
            {
                using (_lock.Lock())
                {
                    Assert.IsFalse(_lock.HasWaiters(c));
                    Assert.That(_lock.GetWaitQueueLength(c), Is.EqualTo(0));
                    c.Await();
                }
            });

            Thread.Sleep(Delays.Short);
            _lock.Lock();
            Assert.IsTrue(_lock.HasWaiters(c));
            Assert.AreEqual(1, _lock.GetWaitQueueLength(c));
            c.Signal();
            _lock.Unlock();

            Thread.Sleep(Delays.Short);
            _lock.Lock();
            Assert.IsFalse(_lock.HasWaiters(c));
            Assert.AreEqual(0, _lock.GetWaitQueueLength(c));
            _lock.Unlock();
            ThreadManager.JoinAndVerify();
        }
        public void AwaitChokesWhenLockIsNotOwned([Values(true, false)] bool isFair)
        {
            _lock = new ReentrantLock(isFair);
            ICondition c = _lock.NewCondition();

            c.Await();
        }
        public void GetWaitingThreadsIncludesWaitingThreads(bool isFair)
        {
            PublicReentrantLock myLock = new PublicReentrantLock(isFair);

            ICondition c = myLock.NewCondition();

            myLock.Lock();
            Assert.That(myLock.GetWaitingThreadsPublic(c).Count, Is.EqualTo(0));
            myLock.Unlock();
            Thread t1 = ThreadManager.StartAndAssertRegistered(
                "T1",
                delegate
            {
                myLock.Lock();
                Assert.That(myLock.GetWaitingThreadsPublic(c).Count, Is.EqualTo(0));
                c.Await();
                myLock.Unlock();
            });

            Thread.Sleep(Delays.Short);
            Thread t2 = ThreadManager.StartAndAssertRegistered(
                "T2",
                delegate
            {
                myLock.Lock();
                Assert.That(myLock.GetWaitingThreadsPublic(c).Count, Is.Not.EqualTo(0));
                c.Await();
                myLock.Unlock();
            });

            Thread.Sleep(Delays.Short);
            myLock.Lock();
            Assert.IsTrue(myLock.HasWaiters(c));
            Assert.IsTrue(myLock.GetWaitingThreadsPublic(c).Contains(t1));
            Assert.IsTrue(myLock.GetWaitingThreadsPublic(c).Contains(t2));
            c.SignalAll();
            myLock.Unlock();

            Thread.Sleep(Delays.Short);
            myLock.Lock();
            Assert.IsFalse(myLock.HasWaiters(c));
            Assert.IsTrue((myLock.GetWaitingThreadsPublic(c).Count == 0));
            myLock.Unlock();

            ThreadManager.JoinAndVerify();
        }
Beispiel #7
0
        public void AwaitNanos_Timeout()
        {
            ReentrantReadWriteLock myLock = new ReentrantReadWriteLock();

            ICondition c = myLock.WriterLock.NewCondition();

            myLock.WriterLock.Lock();
            Assert.IsFalse(c.Await(new TimeSpan(1)));
            myLock.WriterLock.Unlock();
        }
Beispiel #8
0
            public ZKRebalancerListener(
                ZookeeperConsumerConnector parent,
                string group,
                string consumerIdString,
                IDictionary <string, IList <KafkaStream <TKey, TValue> > > kafkaMessageAndMetadataStreams)
            {
                this.parent           = parent;
                this.group            = group;
                this.consumerIdString = consumerIdString;
                this.KafkaMessageAndMetadataStreams = kafkaMessageAndMetadataStreams;

                this.@lock = new ReentrantLock();
                this.cond  = [email protected]();

                this.watcherExecutorThread = new Thread(() =>
                {
                    Logger.InfoFormat("starting watcher executor thread for consumer {0}", consumerIdString);
                    bool doRebalance;
                    while (!parent.isShuttingDown.Get())
                    {
                        try
                        {
                            [email protected]();
                            try
                            {
                                if (!isWatcherTriggered)
                                {
                                    cond.Await(TimeSpan.FromMilliseconds(1000));     // wake up periodically so that it can check the shutdown flag
                                }
                            }
                            finally
                            {
                                doRebalance        = isWatcherTriggered;
                                isWatcherTriggered = false;
                                @lock.Unlock();
                            }

                            if (doRebalance)
                            {
                                this.SyncedRebalance();
                            }
                        }
                        catch (Exception e)
                        {
                            Logger.Error("Error during syncedRebalance", e);
                        }
                    }

                    Logger.InfoFormat("Stoppping watcher executer thread for consumer {0}", consumerIdString);
                });
                this.watcherExecutorThread.Name = consumerIdString + "_watcher_executor";

                this.watcherExecutorThread.Start();
            }
Beispiel #9
0
 public void Run()
 {
     try
     {
         myLock.WriterLock.Lock();
         c.Await();
         myLock.WriterLock.Unlock();
     }
     catch (ThreadInterruptedException)
     {
         Assert.Fail("Should not throw an exception.");
     }
 }
Beispiel #10
0
 public void Run()
 {
     try
     {
         myLock.WriterLock.Lock();
         c.Await(Delays.Medium);
         myLock.WriterLock.Unlock();
         Assert.Fail("Should throw an exception");
     }
     catch (ThreadInterruptedException)
     {
     }
 }
        [Test] public void SignalAllWakesUpAllThreads([Values(true, false)] bool isFair)
        {
            _lock = new ReentrantLock(isFair);
            ICondition  c      = _lock.NewCondition();
            ThreadStart cAwait = delegate { using (_lock.Lock()) c.Await(); };

            ThreadManager.StartAndAssertRegistered("T", cAwait, cAwait);

            Thread.Sleep(Delays.Short);
            _lock.Lock();
            c.SignalAll();
            _lock.Unlock();

            ThreadManager.JoinAndVerify();
        }
        [Test] public void AwaitNanosIsInterruptible([Values(true, false)] bool isFair)
        {
            _lock = new ReentrantLock(isFair);

            ICondition c = _lock.NewCondition();
            Thread     t = ThreadManager.StartAndAssertRegistered(
                "T1",
                () => Assert.Throws <ThreadInterruptedException>(
                    () => { using (_lock.Lock()) c.Await(new TimeSpan(0, 0, 0, 1)); }));

            Thread.Sleep(Delays.Short);
            t.Interrupt();

            ThreadManager.JoinAndVerify();
        }
        [Test] public void AwaitReturnsWhenSignalled([Values(true, false)] bool isFair)
        {
            _lock = new ReentrantLock(isFair);
            ICondition c = _lock.NewCondition();

            ThreadManager.StartAndAssertRegistered(
                "T1",
                () => { using (_lock.Lock()) c.Await(); });

            Thread.Sleep(Delays.Short);
            _lock.Lock();
            c.Signal();
            _lock.Unlock();
            ThreadManager.JoinAndVerify();
        }
Beispiel #14
0
        /// <summary>
        /// This method will remove and return the item in the front of the queue if one exists, or
        /// it will block the current thread until there is an item to dequeue.
        /// </summary>
        /// <returns>
        /// The <c>T</c> item in the front of the queue.
        /// </returns>
        public T Dequeue()
        {
            _lock.Lock();
            try {
                while (_queue.Count == 0)
                {
                    _notEmpty.Await();
                }

                return(_queue.Dequeue());
            }
            finally {
                _lock.Unlock();
            }
        }
Beispiel #15
0
 /// <summary>
 /// <inheritDoc/>
 ///
 /// </summary>
 public override void Run()
 {
     try
     {
         while (doRun)
         {
             // Wait for a request
             IBiConsumer <StanfordCoreNLPClient.Backend, IConsumer <StanfordCoreNLPClient.Backend> > request;
             StanfordCoreNLPClient.Backend annotator;
             stateLock.Lock();
             try
             {
                 while (queue.IsEmpty())
                 {
                     enqueued.Await();
                     if (!doRun)
                     {
                         return;
                     }
                 }
                 // Get the actual request
                 request = queue.Poll();
                 // We have a request
                 // Find a free annotator
                 while (freeAnnotators.IsEmpty())
                 {
                     newlyFree.Await();
                 }
                 annotator = freeAnnotators.Poll();
             }
             finally
             {
                 stateLock.Unlock();
             }
             // We have an annotator
             // Run the annotation
             request.Accept(annotator, null);
         }
     }
     catch (Exception e)
     {
         // ASYNC: we've freed this annotator
         // add it back to the queue and register it as available
         // If the queue is empty, and all the annotators have returned, we're done
         // Annotator is running (in parallel, most likely)
         throw new Exception(e);
     }
 }
Beispiel #16
0
        public void Await_IllegalMonitor()
        {
            ReentrantReadWriteLock myLock = new ReentrantReadWriteLock();

            ICondition c = myLock.WriterLock.NewCondition();

            try
            {
                c.Await();
                Assert.Fail("Should throw an exception.");
            }

            catch (SynchronizationLockException)
            {
            }
        }
Beispiel #17
0
        /// <summary>
        /// This method adds an item to the queue.
        /// </summary>
        /// <param name="item">
        /// The item to push into the queue.
        /// </param>
        public void Enqueue(T item)
        {
            _lock.Lock();
            try {
                while (_buffer.Count == _capacity)
                {
                    _notFull.Await();
                }

                _buffer.Enqueue(item);
                _notEmpty.Signal();
            }
            finally {
                _lock.Unlock();
            }
        }
Beispiel #18
0
        /// <summary>
        /// This method will remove and return the item in the front of the queue if one exists, or
        /// it will block the current thread until there is an item to dequeue.
        /// </summary>
        /// <returns>
        /// The <c>T</c> item in the front of the queue.
        /// </returns>
        public T Dequeue()
        {
            _lock.Lock();
            try {
                while (_buffer.Count == 0)
                {
                    _notEmpty.Await();
                }

                T result = _buffer.Dequeue();
                _notFull.Signal();

                return(result);
            }
            finally {
                _lock.Unlock();
            }
        }
        [Test] public void AwaitTimeoutWithoutSignal([Values(true, false)] bool isFair)
        {
            TimeSpan timeToWait = Delays.Short;

            _lock = new ReentrantLock(isFair);
            ICondition c = _lock.NewCondition();

            _lock.Lock();
            Stopwatch sw = new Stopwatch();

            sw.Start();
            bool result = c.Await(timeToWait);

            sw.Stop();
            Assert.IsFalse(result);
            Assert.That(sw.Elapsed + TimeSpan.FromMilliseconds(0.5), Is.Not.LessThan(timeToWait));
            _lock.Unlock();
        }
Beispiel #20
0
        /// <summary>
        /// <inheritDoc/>
        /// This method creates an async call to the server, and blocks until the server
        /// has finished annotating the object.
        /// </summary>
        public override void Annotate(Annotation annotation)
        {
            ILock      Lock           = new ReentrantLock();
            ICondition annotationDone = Lock.NewCondition();

            Annotate(Java.Util.Collections.Singleton(annotation), 1, null);
            try
            {
                Lock.Lock();
                annotationDone.Await();
            }
            catch (Exception)
            {
                // Only wait for one callback to complete; only annotating one document
                log.Info("Interrupt while waiting for annotation to return");
            }
            finally
            {
                Lock.Unlock();
            }
        }
Beispiel #21
0
 public void ExtWait(ExtMutex mutex)
 {
     m_cond.Await();
 }