예제 #1
0
        /// <summary>
        /// Does the real work for all <c>Drain</c> methods. Caller must
        /// guarantee the <paramref name="action"/> is not <c>null</c> and
        /// <paramref name="maxElements"/> is greater then zero (0).
        /// </summary>
        /// <seealso cref="IBlockingQueue{T}.DrainTo(ICollection{T})"/>
        /// <seealso cref="IBlockingQueue{T}.DrainTo(ICollection{T}, int)"/>
        /// <seealso cref="IBlockingQueue{T}.Drain(System.Action{T})"/>
        /// <seealso cref="IBlockingQueue{T}.DrainTo(ICollection{T},int)"/>
        protected override int DoDrainTo(Action <T> action, int maxElements)
        {
            ReentrantLock currentLock = _lock;

            currentLock.Lock();
            try
            {
                T   element;
                int n;
                for (n = 0; n < maxElements && _wrapped.Poll(out element); n++)
                {
                    action(element);
                }
                if (n == 1)
                {
                    _notFullCondition.Signal();
                }
                else if (n != 0)
                {
                    _notFullCondition.SignalAll();
                }
                return(n);
            }
            finally
            {
                currentLock.Unlock();
            }
        }
예제 #2
0
        /**
         * @param dataFile file containing preferences data
         * @throws FileNotFoundException if dataFile does not exist
         */
        public FileDataModel(String dataFile, bool autoReload)
        {
            if (String.IsNullOrEmpty(dataFile))
            {
                throw new ArgumentNullException("dataFile is null");
            }
            if (File.Exists(dataFile))
            {
                throw new FileNotFoundException(dataFile);
            }

            if (log.IsInfoEnabled)
            {
                log.Info("Creating FileDataModel for file " + dataFile);
            }

            this.dataFile     = dataFile;
            this.lastModified = File.GetLastWriteTime(dataFile);
            this.refreshLock  = new ReentrantLock();
            this.reloadLock   = new ReentrantLock();

            this.useReload = autoReload;
            if (autoReload)
            {
                // Create the delegate that invokes methods for the timer.
                TimerCallback timerDelegate =
                    new TimerCallback(CheckStatus);

                // Schedule next refresh
                timer = new Timer(timerDelegate, this, RELOAD_CHECK_INTERVAL_MS, RELOAD_CHECK_INTERVAL_MS);
            }
        }
예제 #3
0
            public Deadlock()
            {
                TestTimedOutTestsListener.Deadlock.DeadlockThread[] dThreads = new TestTimedOutTestsListener.Deadlock.DeadlockThread
                                                                               [6];
                TestTimedOutTestsListener.Deadlock.Monitor a = new TestTimedOutTestsListener.Deadlock.Monitor
                                                                   (this, "a");
                TestTimedOutTestsListener.Deadlock.Monitor b = new TestTimedOutTestsListener.Deadlock.Monitor
                                                                   (this, "b");
                TestTimedOutTestsListener.Deadlock.Monitor c = new TestTimedOutTestsListener.Deadlock.Monitor
                                                                   (this, "c");
                dThreads[0] = new TestTimedOutTestsListener.Deadlock.DeadlockThread(this, "MThread-1"
                                                                                    , a, b);
                dThreads[1] = new TestTimedOutTestsListener.Deadlock.DeadlockThread(this, "MThread-2"
                                                                                    , b, c);
                dThreads[2] = new TestTimedOutTestsListener.Deadlock.DeadlockThread(this, "MThread-3"
                                                                                    , c, a);
                Lock d = new ReentrantLock();
                Lock e = new ReentrantLock();
                Lock f = new ReentrantLock();

                dThreads[3] = new TestTimedOutTestsListener.Deadlock.DeadlockThread(this, "SThread-4"
                                                                                    , d, e);
                dThreads[4] = new TestTimedOutTestsListener.Deadlock.DeadlockThread(this, "SThread-5"
                                                                                    , e, f);
                dThreads[5] = new TestTimedOutTestsListener.Deadlock.DeadlockThread(this, "SThread-6"
                                                                                    , f, d);
                // make them daemon threads so that the test will exit
                for (int i = 0; i < 6; i++)
                {
                    dThreads[i].SetDaemon(true);
                    dThreads[i].Start();
                }
            }
예제 #4
0
 public ItemAverageRecommender(DataModel dataModel)
     : base(dataModel)
 {
     this.itemAverages      = new Dictionary <Object, RunningAverage>(1003);
     this.refreshLock       = new ReentrantLock();
     this.buildAveragesLock = new ReaderWriterLock();
 }
예제 #5
0
        /// <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 currentLock = _lock;

            currentLock.LockInterruptibly();
            try
            {
                try
                {
                    T element;
                    while (!_wrapped.Poll(out element))
                    {
                        _notEmptyCondition.Await();
                    }
                    _notFullCondition.Signal();
                    return(element);
                }
                catch (ThreadInterruptedException)
                {
                    _notEmptyCondition.Signal();
                    throw;
                }
            }
            finally
            {
                currentLock.Unlock();
            }
        }
예제 #6
0
        /// <summary>
        /// Retrieves and removes the head of this queue, waiting up to the
        /// specified wait time if necessary for an element to become available.
        /// </summary>
        /// <param name="element">
        /// Set to the head of this queue. <c>default(T)</c> if queue is empty.
        /// </param>
        /// <param name="duration">How long to wait before giving up.</param>
        /// <returns>
        /// <c>false</c> if the queue is still empty after waited for the time
        /// specified by the <paramref name="duration"/>. Otherwise <c>true</c>.
        /// </returns>
        public override bool Poll(TimeSpan duration, out T element)
        {
            ReentrantLock currentLock = _lock;

            currentLock.LockInterruptibly();
            try
            {
                TimeSpan durationToWait = duration;
                DateTime deadline       = DateTime.Now.Add(durationToWait);
                while (!_wrapped.Poll(out element))
                {
                    if (durationToWait.Ticks <= 0)
                    {
                        element = default(T);
                        return(false);
                    }
                    try
                    {
                        _notEmptyCondition.Await(durationToWait);
                        durationToWait = deadline.Subtract(DateTime.Now);
                    }
                    catch (ThreadInterruptedException)
                    {
                        _notEmptyCondition.Signal();
                        throw;
                    }
                }
                _notFullCondition.Signal();
                return(true);
            }
            finally
            {
                currentLock.Unlock();
            }
        }
예제 #7
0
        /// <summary>
        /// Returns an array containing all of the elements in this queue; the
        /// runtime type of the returned array is that of the specified array.
        /// The returned array elements are in no particular order.
        /// If the queue fits in the specified array, it is returned therein.
        /// Otherwise, a new array is allocated with the runtime type of the
        /// specified array and the size of this queue.
        ///
        /// <p>If this queue fits in the specified array with room to spare
        /// (i.e., the array has more elements than this queue), the element in
        /// the array immediately following the end of the queue is set to
        /// <tt>null</tt>.</p>
        ///
        /// <p>Like the {@link #toArray()} method, this method acts as bridge between
        /// array-based and collection-based APIs.  Further, this method allows
        /// precise control over the runtime type of the output array, and may,
        /// under certain circumstances, be used to save allocation costs.</p>
        ///
        /// <p>Suppose <tt>x</tt> is a queue known to contain only strings.
        /// The following code can be used to dump the queue into a newly
        /// allocated array of <tt>String</tt>:</p>
        ///
        /// <pre>
        ///     String[] y = x.toArray(new String[0]);</pre>
        ///
        /// Note that <tt>toArray(new Object[0])</tt> is identical in function to
        /// <tt>toArray()</tt>.
        /// </summary>
        /// <param name="target">the array into which the elements of the queue are to
        /// be stored, if it is big enough; otherwise, a new array of the
        /// same runtime type is allocated for this purpose</param>
        /// <exception cref="ArgumentNullException">if <paramref name="target"/> is null</exception>
        public T[] ToArray(T[] target)
        {
            if (target == null)
            {
                throw new ArgumentNullException("target must not be null");
            }
            ReentrantLock rl = _lock;

            rl.Lock();
            try {
                int targetSize = target.Length;
                int sourceSize = Count;
                if (targetSize < sourceSize)
                {
                    target = new T[sourceSize];
                }

                int k = 0;
                foreach (T item in _innerQueue)
                {
                    target[k++] = item;
                }
                for (; targetSize < sourceSize; targetSize++)
                {
                    target[targetSize] = default(T);
                }

                return(target);
            }
            finally {
                rl.Unlock();
            }
        }
예제 #8
0
        /// <summary>
        /// Inserts the specified element into this queue, waiting if necessary
        /// for space to become available.
        /// </summary>
        /// <param name="element">the element to add</param>
        /// <exception cref="System.ArgumentNullException">
        /// If the specified element is <see langword="null"/> and this queue
        /// does not permit <see langword="null"/> elements.
        /// </exception>
        /// <exception cref="System.ArgumentException">
        /// If some property of the supplied <paramref name="element"/> prevents
        /// it from being added to this queue.
        /// </exception>
        public override void Put(T element)
        {
            ReentrantLock currentLock = _lock;

            currentLock.LockInterruptibly();
            try
            {
                try
                {
                    while (!_wrapped.Offer(element))
                    {
                        _notFullCondition.Await();
                    }
                    _notEmptyCondition.Signal();
                }
                catch (ThreadInterruptedException)
                {
                    _notFullCondition.Signal();
                    throw;
                }
            }
            finally
            {
                currentLock.Unlock();
            }
        }
예제 #9
0
 public DataChange(ReentrantLock dataLock, ICondition dataExistsOrChanged, ZkClient zkClient)
 {
     Console.WriteLine("init data change...");
     this.dataLock            = dataLock;
     this.dataExistsOrChanged = dataExistsOrChanged;
     this.zkClient            = zkClient;
 }
예제 #10
0
        /// <summary>
        /// Retrieves and removes the head of this queue, waiting up to the
        /// specified wait time if necessary for an element to become available.
        /// </summary>
        /// <param name="timeout">how long to wait before giving up</param>
        /// <param name="element"></param>
        /// <returns>
        /// the head of this queue, or <see lang="default(T)"/> if the
        /// specified waiting time elapses before an element is available.
        /// </returns>
        public override bool Poll(TimeSpan timeout, out T element)
        {
            ReentrantLock rl = _lock;

            rl.LockInterruptibly();
            try {
                DateTime deadline = DateTime.Now + timeout;
                for (; ;)
                {
                    if (_innerQueue.Poll(out element))
                    {
                        return(true);
                    }
                    if (timeout.TotalMilliseconds <= 0)
                    {
                        return(false);
                    }
                    try {
                        notEmpty.Await(timeout);
                        timeout = deadline - DateTime.Now;
                    }
                    catch (ThreadInterruptedException) {
                        notEmpty.Signal(); // propagate to non-interrupted thread
                        throw;
                    }
                }
            }
            finally {
                rl.Unlock();
            }
        }
예제 #11
0
        /**
         * @throws UnsupportedOperationException {@inheritDoc}
         * @throws ClassCastException            {@inheritDoc}
         * @throws NullPointerException          {@inheritDoc}
         * @throws IllegalArgumentException      {@inheritDoc}
         */
        //TODO: do we really need this? can we leave it to base class?
        public override int DrainTo(ICollection <T> collection)
        {
            if (collection == null)
            {
                throw new ArgumentNullException("collection", "must not be null");
            }
            if (collection == this)
            {
                throw new ArgumentException("cannot DrainTo this");
            }
            ReentrantLock rl = _lock;

            rl.Lock();
            try {
                int n = 0;
                T   element;
                while (_innerQueue.Poll(out element))
                {
                    collection.Add(element);
                    ++n;
                }
                return(n);
            }
            finally {
                rl.Unlock();
            }
        }
예제 #12
0
        /// <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();
            }
        }
예제 #13
0
        /**
         * Retrieves and removes the head of this queue, if another thread
         * is currently making an element available.
         *
         * @return the head of this queue, or <tt>null</tt> if no
         *         element is available.
         */
        public override bool Poll(out T element)
        {
            ReentrantLock qlock = _qlock;

            for (; ;)
            {
                Node node;
                qlock.Lock();
                try
                {
                    node = _waitingProducers.Dequeue();
                }
                finally
                {
                    qlock.Unlock();
                }
                if (node == null)
                {
                    element = default(T);
                    return(false);
                }

                else
                {
                    T x;
                    if (node.GetItem(out x))
                    {
                        element = x;
                        return(true);
                    }
                    // else retry
                }
            }
        }
예제 #14
0
        // Untimed nonblocking versions

        /// <summary>
        /// Inserts the specified element into this queue, if another thread is
        /// waiting to receive it.
        /// </summary>
        /// <param name="element">the element to add</param>
        /// <returns><tt>true</tt> if the element was added to this queue, else <tt>false</tt></returns>
        /// <exception cref="ArgumentNullException" />
        public override bool Offer(T element)
        {
            if (element == null)
            {
                throw new ArgumentNullException("element");
            }
            ReentrantLock qlock = _qlock;

            for (; ;)
            {
                Node node;
                qlock.Lock();
                try
                {
                    node = _waitingConsumers.Dequeue();
                }
                finally
                {
                    qlock.Unlock();
                }
                if (node == null)
                {
                    return(false);
                }

                else if (node.SetItem(element))
                {
                    return(true);
                }
                // else retry
            }
        }
예제 #15
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="dataModel"><see cref="taste.Model.DataModel">DataModel</see> which provides <see cref="taste.mode.User">User</see>s</param>
 /// <param name="clusterSimilarity"><see cref="taste.Recommender.ClusterSimilarity">ClusterSimilarity</see> used to compute cluster similarity</param>
 /// <param name="numClusters">desired number of clusters to create</param>
 /// <param name="samplingPercentage">
 /// percentage of all cluster-cluster pairs to consider when finding
 /// next-most-similar clusters. Decreasing this value from 1.0 can increase performance at the
 /// cost of accuracy
 /// </param>
 public TreeClusteringRecommender(DataModel dataModel,
                                  ClusterSimilarity clusterSimilarity,
                                  int numClusters,
                                  double samplingPercentage)
     : base(dataModel)
 {
     if (clusterSimilarity == null)
     {
         throw new ArgumentNullException("clusterSimilarity is null");
     }
     if (numClusters < 2)
     {
         throw new ArgumentException("numClusters must be at least 2");
     }
     if (double.IsNaN(samplingPercentage) || samplingPercentage <= 0.0 || samplingPercentage > 1.0)
     {
         throw new ArgumentException("samplingPercentage is invalid: " + samplingPercentage);
     }
     this.clusterSimilarity     = clusterSimilarity;
     this.numClusters           = numClusters;
     this.clusteringThreshold   = Double.NaN;
     this.clusteringByThreshold = false;
     this.samplingPercentage    = samplingPercentage;
     this.refreshLock           = new ReentrantLock();
     this.buildClustersLock     = new ReentrantLock();
 }
예제 #16
0
 /// <summary>
 /// </summary>
 /// <param name="dataModel">
 /// <see cref="taste.Model.DataModel">DataModel</see> which provides <see cref="taste.Model.User">User</see>s
 /// </param>
 /// <param name="clusterSimilarity">
 /// <see cref="taste.Recommender.ClusterSimilarity">ClusterSimilarity</see> used to compute cluster similarity
 /// </param>
 /// <param name="clusteringThreshold">clustering similarity threshold; clusters will be aggregated
 /// into larger clusters until the next two nearest clusters' similarity drops below this threshold
 /// </param>
 /// <param name="samplingPercentage">
 /// percentage of all cluster-cluster pairs to consider when finding next-most-similar
 /// clusters. Decreasing this value from 1.0 can increase performance at the cost of accuracy
 /// </param>
 /// <remarks>
 /// Throws ArgumentException if arguments are <code>null</code>, or <code>clusteringThreshold</code> is
 /// {@link Double#NaN}, or samplingPercentage is {@link Double#NaN} or nonpositive or greater than 1.0
 /// </remarks>
 public TreeClusteringRecommender(DataModel dataModel,
                                  ClusterSimilarity clusterSimilarity,
                                  double clusteringThreshold,
                                  double samplingPercentage)
     : base(dataModel)
 {
     if (clusterSimilarity == null)
     {
         throw new ArgumentNullException("clusterSimilarity is null");
     }
     if (double.IsNaN(clusteringThreshold))
     {
         throw new ArgumentException("clusteringThreshold must not be NaN");
     }
     if (double.IsNaN(samplingPercentage) || samplingPercentage <= 0.0 || samplingPercentage > 1.0)
     {
         throw new ArgumentException("samplingPercentage is invalid: " + samplingPercentage);
     }
     this.clusterSimilarity     = clusterSimilarity;
     this.numClusters           = int.MinValue;
     this.clusteringThreshold   = clusteringThreshold;
     this.clusteringByThreshold = true;
     this.samplingPercentage    = samplingPercentage;
     this.refreshLock           = new ReentrantLock();
     this.buildClustersLock     = new ReentrantLock();
 }
예제 #17
0
        /// <summary>
        /// The default ctor
        /// </summary>
        public InMemoryCookieStore()
        {
            CookieJar   = new List <HttpCookie>();
            DomainIndex = new Dictionary <String, IList <HttpCookie> >();
            UriIndex    = new Dictionary <URI, IList <HttpCookie> >();

            @lock = new ReentrantLock(false);
        }
예제 #18
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="intervalMillis">The interval in milliseconds.</param>
 /// <param name="threadName">The thread name.</param>
 /// <param name="doUpdate">A delegate to call to perform the update.</param>
 /// <param name="handleException">A delegate to call to handle an exception.</param>
 /// <param name="lock"></param>
 public ReplicationThread(long intervalMillis, string threadName, Action doUpdate, Action<Exception> handleException, ReentrantLock @lock)
 {
     this.doUpdate = doUpdate;
     this.handleException = handleException;
     this.@lock = @lock;
     Name = threadName;
     this.interval = intervalMillis;
 }
예제 #19
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="intervalMillis">The interval in milliseconds.</param>
 /// <param name="threadName">The thread name.</param>
 /// <param name="doUpdate">A delegate to call to perform the update.</param>
 /// <param name="handleUpdateException">A delegate to call to handle an exception.</param>
 /// <param name="updateLock"></param>
 public ReplicationThread(long intervalMillis, string threadName, Action doUpdate, Action <Exception> handleUpdateException, ReentrantLock updateLock)
     : base(threadName)
 {
     this.intervalMillis        = intervalMillis;
     this.doUpdate              = doUpdate ?? throw new ArgumentNullException(nameof(doUpdate));
     this.handleUpdateException = handleUpdateException ?? throw new ArgumentNullException(nameof(handleUpdateException));
     this.updateLock            = updateLock ?? throw new ArgumentNullException(nameof(updateLock));
 }
예제 #20
0
 /**
  * \brief The activity onDestroy function
  */
 protected override void OnDestroy()
 {
     prepareForTermination();
     base.OnDestroy();
     destroyMediaPlayer();
     mMediaPlayerLock     = null;
     mMediaControllerLock = null;
 }
 /// <summary>Constructor.</summary>
 /// <param name="initialCapacity"/>
 public ConcurrentHashIndex(int initialCapacity)
 {
     item2Index = new ConcurrentHashMap <E, int>(initialCapacity);
     indexSize  = 0;
     Lock       = new ReentrantLock();
     object[] arr = new object[initialCapacity];
     index2Item = new AtomicReference <object[]>(arr);
 }
예제 #22
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void forceCheckPointShouldWaitTheCurrentCheckPointingToCompleteBeforeRunning() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ForceCheckPointShouldWaitTheCurrentCheckPointingToCompleteBeforeRunning()
        {
            // Given
            Lock @lock = new ReentrantLock();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.locks.Lock spyLock = spy(lock);
            Lock spyLock = spy(@lock);

            doAnswer(invocation =>
            {
                verify(_appender).checkPoint(any(typeof(LogPosition)), any(typeof(LogCheckPointEvent)));
                reset(_appender);
                invocation.callRealMethod();
                return(null);
            }).when(spyLock).unlock();

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final CheckPointerImpl checkPointing = checkPointer(mutex(spyLock));
            CheckPointerImpl checkPointing = CheckPointer(Mutex(spyLock));

            MockTxIdStore();

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.CountDownLatch startSignal = new java.util.concurrent.CountDownLatch(2);
            System.Threading.CountdownEvent startSignal = new System.Threading.CountdownEvent(2);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.CountDownLatch completed = new java.util.concurrent.CountDownLatch(2);
            System.Threading.CountdownEvent completed = new System.Threading.CountdownEvent(2);

            checkPointing.Start();

            Thread checkPointerThread = new CheckPointerThread(checkPointing, startSignal, completed);

            Thread forceCheckPointThread = new Thread(() =>
            {
                try
                {
                    startSignal.Signal();
                    startSignal.await();
                    checkPointing.ForceCheckPoint(_info);

                    completed.Signal();
                }
                catch (Exception e)
                {
                    throw new Exception(e);
                }
            });

            // when
            checkPointerThread.Start();
            forceCheckPointThread.Start();

            completed.await();

            verify(spyLock, times(2)).@lock();
            verify(spyLock, times(2)).unlock();
        }
예제 #23
0
 public _Runnable_149(AtomicInteger handled, int SocketNum, ReentrantLock Lock, AList
                      <DomainSocket[]> pairs, DomainSocketWatcher watcher)
 {
     this.handled   = handled;
     this.SocketNum = SocketNum;
     this.Lock      = Lock;
     this.pairs     = pairs;
     this.watcher   = watcher;
 }
예제 #24
0
 /// <summary>Wrap a ProgressMonitor to be thread safe.</summary>
 /// <remarks>Wrap a ProgressMonitor to be thread safe.</remarks>
 /// <param name="pm">the underlying monitor to receive events.</param>
 public ThreadSafeProgressMonitor(ProgressMonitor pm)
 {
     this.pm             = pm;
     this.Lock           = new ReentrantLock();
     this.mainThread     = Sharpen.Thread.CurrentThread();
     this.workers        = new AtomicInteger(0);
     this.pendingUpdates = new AtomicInteger(0);
     this.process        = Sharpen.Extensions.CreateSemaphore(0);
 }
예제 #25
0
 protected AbstractRecommender(DataModel dataModel)
 {
     if (dataModel == null)
     {
         throw new ArgumentNullException("dataModel is null");
     }
     this.dataModel   = dataModel;
     this.refreshLock = new ReentrantLock();
 }
예제 #26
0
 public SpearmanCorrelation(UserCorrelation rankingUserCorrelation)
 {
     if (rankingUserCorrelation == null)
     {
         throw new ArgumentNullException("rankingUserCorrelation is null");
     }
     this.rankingUserCorrelation = rankingUserCorrelation;
     this.refreshLock            = new ReentrantLock();
 }
예제 #27
0
 public SpearmanCorrelation(DataModel dataModel)
 {
     if (dataModel == null)
     {
         throw new ArgumentNullException("dataModel is null");
     }
     this.rankingUserCorrelation = new PearsonCorrelation(dataModel);
     this.refreshLock            = new ReentrantLock();
 }
예제 #28
0
        public BlockingBuffer(int capacity)
        {
            _capacity = capacity;

            _buffer   = new Queue <T>(_capacity);
            _lock     = new ReentrantLock();
            _notFull  = _lock.NewCondition();
            _notEmpty = _lock.NewCondition();
        }
 public LeaderExistsOrChangedListener(string topic, int partition, ReentrantLock leaderLock, ICondition leaderExistsOrChanged, int?oldLeaderOpt, ZkClient zkClient)
 {
     this.topic                 = topic;
     this.partition             = partition;
     this.leaderLock            = leaderLock;
     this.leaderExistsOrChanged = leaderExistsOrChanged;
     this.oldLeaderOpt          = oldLeaderOpt;
     this.zkClient              = zkClient;
 }
예제 #30
0
        private WindowCache(WindowCacheConfig cfg)
        {
            tableSize = TableSize(cfg);
            int lockCount = LockCount(cfg);

            if (tableSize < 1)
            {
                throw new ArgumentException(JGitText.Get().tSizeMustBeGreaterOrEqual1);
            }
            if (lockCount < 1)
            {
                throw new ArgumentException(JGitText.Get().lockCountMustBeGreaterOrEqual1);
            }
            queue = new ReferenceQueue <ByteWindow>();
            clock = new AtomicLong(1);
            table = new AtomicReferenceArray <WindowCache.Entry>(tableSize);
            locks = new WindowCache.Lock[lockCount];
            for (int i = 0; i < locks.Length; i++)
            {
                locks[i] = new WindowCache.Lock();
            }
            evictLock = new ReentrantLock();
            int eb = (int)(tableSize * .1);

            if (64 < eb)
            {
                eb = 64;
            }
            else
            {
                if (eb < 4)
                {
                    eb = 4;
                }
            }
            if (tableSize < eb)
            {
                eb = tableSize;
            }
            evictBatch      = eb;
            maxFiles        = cfg.GetPackedGitOpenFiles();
            maxBytes        = cfg.GetPackedGitLimit();
            mmap            = cfg.IsPackedGitMMAP();
            windowSizeShift = Bits(cfg.GetPackedGitWindowSize());
            windowSize      = 1 << windowSizeShift;
            openFiles       = new AtomicInteger();
            openBytes       = new AtomicLong();
            if (maxFiles < 1)
            {
                throw new ArgumentException(JGitText.Get().openFilesMustBeAtLeast1);
            }
            if (maxBytes < windowSize)
            {
                throw new ArgumentException(JGitText.Get().windowSizeMustBeLesserThanLimit);
            }
        }