Esempio n. 1
0
 public bool MoveNext()
 {
     using (_lock.Lock())
     {
         return(_wrapped.MoveNext());
     }
 }
Esempio n. 2
0
 /// <summary>Close the DomainSocketWatcher and wait for its thread to terminate.</summary>
 /// <remarks>
 /// Close the DomainSocketWatcher and wait for its thread to terminate.
 /// If there is more than one close, all but the first will be ignored.
 /// </remarks>
 /// <exception cref="System.IO.IOException"/>
 public void Close()
 {
     Lock.Lock();
     try
     {
         if (closed)
         {
             return;
         }
         if (Log.IsDebugEnabled())
         {
             Log.Debug(this + ": closing");
         }
         closed = true;
     }
     finally
     {
         Lock.Unlock();
     }
     // Close notificationSockets[0], so that notificationSockets[1] gets an EOF
     // event.  This will wake up the thread immediately if it is blocked inside
     // the select() system call.
     notificationSockets[0].Close();
     // Wait for the select thread to terminate.
     Uninterruptibles.JoinUninterruptibly(watcherThread);
 }
Esempio n. 3
0
 protected override T FetchCurrent()
 {
     using (_lock.Lock())
     {
         return(_wrapped.Current);
     }
 }
        public void Dispose()
        {
            lock (this)
            {
                //System.out.println("NRT: set finish");

                Finish = true;

                // So thread wakes up and notices it should finish:
                ReopenLock.Lock();
                try
                {
                    ReopenCond.Set();
                }
                finally
                {
                    ReopenLock.Unlock();
                }

                try
                {
                    Join();
                }
                catch (ThreadInterruptedException ie)
                {
                    throw new ThreadInterruptedException(ie);
                }

                // Max it out so any waiting search threads will return:
                SearchingGen = long.MaxValue;
                Monitor.PulseAll(this);
            }
        }
Esempio n. 5
0
        /**
         * \brief Create the media player and load video
         */
        private void createMediaPlayer()
        {
            mMediaPlayerLock.Lock();
            mMediaControllerLock.Lock();

            mMediaPlayer     = new MediaPlayer();
            mMediaController = new MediaController(this);

            AssetFileDescriptor afd = null;
            bool fileExist          = true;

            try
            {
                afd = Assets.OpenFd(mMovieUrl);
            }
            catch (IOException e)
            {
                fileExist = false;
            }
            if (afd == null)
            {
                fileExist = false;
            }
            try
            {
                if (fileExist)
                {
                    mMediaPlayer.SetDataSource(afd.FileDescriptor, afd.StartOffset, afd.Length);
                    afd.Close();
                }
                else
                {
                    string URL_REGEX          = "^((https?|ftp)://|(www|ftp)\\.)[a-z0-9-]+(\\.[a-z0-9-]+)+((:[0-9]+)|)+([/?].*)?$"; //should be ok
                    Java.Util.Regex.Pattern p = Java.Util.Regex.Pattern.Compile(URL_REGEX);
                    Java.Util.Regex.Matcher m = p.Matcher(mMovieUrl);                                                               //replace with string to compare
                    if (m.Find())
                    {
                        mMediaPlayer.SetDataSource(mMovieUrl);
                    }
                }

                mMediaPlayer.SetDisplay(mHolder);
                mMediaPlayer.PrepareAsync();
                mMediaPlayer.SetOnPreparedListener(this);
                mMediaPlayer.SetOnErrorListener(this);
                mMediaPlayer.SetOnCompletionListener(this);
                mMediaPlayer.SetAudioStreamType(Stream.Music);
            }
            catch (Exception e)
            {
                Log.Error("PikkartFullscreenVideo", "error while creating the MediaPlayer: " + e.ToString());
                prepareForTermination();
                destroyMediaPlayer();
                Finish();
            }

            mMediaControllerLock.Unlock();
            mMediaPlayerLock.Unlock();
        }
Esempio n. 6
0
        /**
         * \brief Deinitialization, unload stuff and release surface texture.
         */
        public void deinit()
        {
            unload();

            mSurfaceTextureLock.Lock();
            mSurfaceTexture = null;
            mSurfaceTextureLock.Unlock();
        }
Esempio n. 7
0
 /// <summary>
 /// This method handles the following conditions:
 /// <ul>
 /// <li>If retry is not to be processed, return null</li>
 /// <li>If there is no cache entry, add a new entry
 /// <paramref name="newEntry"/>
 /// and return
 /// it.</li>
 /// <li>If there is an existing entry, wait for its completion. If the
 /// completion state is
 /// <see cref="CacheEntry.Failed"/>
 /// , the expectation is that the
 /// thread that waited for completion, retries the request. the
 /// <see cref="CacheEntry"/>
 /// state is set to
 /// <see cref="CacheEntry.Inprogress"/>
 /// again.
 /// <li>If the completion state is
 /// <see cref="CacheEntry.Success"/>
 /// , the entry is
 /// returned so that the thread that waits for it can can return previous
 /// response.</li>
 /// <ul>
 /// </summary>
 /// <returns>
 ///
 /// <see cref="CacheEntry"/>
 /// .
 /// </returns>
 private RetryCache.CacheEntry WaitForCompletion(RetryCache.CacheEntry newEntry)
 {
     RetryCache.CacheEntry mapEntry = null;
     Lock.Lock();
     try
     {
         mapEntry = set.Get(newEntry);
         // If an entry in the cache does not exist, add a new one
         if (mapEntry == null)
         {
             if (Log.IsTraceEnabled())
             {
                 Log.Trace("Adding Rpc request clientId " + newEntry.clientIdMsb + newEntry.clientIdLsb
                           + " callId " + newEntry.callId + " to retryCache");
             }
             set.Put(newEntry);
             retryCacheMetrics.IncrCacheUpdated();
             return(newEntry);
         }
         else
         {
             retryCacheMetrics.IncrCacheHit();
         }
     }
     finally
     {
         Lock.Unlock();
     }
     // Entry already exists in cache. Wait for completion and return its state
     Preconditions.CheckNotNull(mapEntry, "Entry from the cache should not be null");
     // Wait for in progress request to complete
     lock (mapEntry)
     {
         while (mapEntry.state == RetryCache.CacheEntry.Inprogress)
         {
             try
             {
                 Runtime.Wait(mapEntry);
             }
             catch (Exception)
             {
                 // Restore the interrupted status
                 Thread.CurrentThread().Interrupt();
             }
         }
         // Previous request has failed, the expectation is is that it will be
         // retried again.
         if (mapEntry.state != RetryCache.CacheEntry.Success)
         {
             mapEntry.state = RetryCache.CacheEntry.Inprogress;
         }
     }
     return(mapEntry);
 }
Esempio n. 8
0
 internal override bool CanCache(int length, ObjectToPack src, ObjectToPack res)
 {
     Lock.Lock();
     try
     {
         return(base.CanCache(length, src, res));
     }
     finally
     {
         Lock.Unlock();
     }
 }
        /**
         * @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();
            }
        }
Esempio n. 10
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
                }
            }
        }
Esempio n. 11
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
            }
        }
Esempio n. 12
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();
            }
        }
Esempio n. 13
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();
            }
        }
Esempio n. 14
0
            public TopFieldDocs Call()
            {
                Debug.Assert(Slice.Leaves.Length == 1);
                TopFieldDocs docs = Searcher.Search(Arrays.AsList(Slice.Leaves), Weight, After, NDocs, Sort, true, DoDocScores || Sort.NeedsScores(), DoMaxScore);

                @lock.Lock();
                try
                {
                    AtomicReaderContext ctx = Slice.Leaves[0];
                    int @base = ctx.DocBase;
                    Hq.NextReader = ctx;
                    Hq.Scorer     = FakeScorer;
                    foreach (ScoreDoc scoreDoc in docs.ScoreDocs)
                    {
                        FakeScorer.doc   = scoreDoc.Doc - @base;
                        FakeScorer.score = scoreDoc.Score;
                        Hq.Collect(scoreDoc.Doc - @base);
                    }

                    // Carry over maxScore from sub:
                    if (DoMaxScore && docs.MaxScore > Hq.MaxScore)
                    {
                        Hq.MaxScore = docs.MaxScore;
                    }
                }
                finally
                {
                    @lock.Unlock();
                }
                return(docs);
            }
Esempio n. 15
0
            public TopFieldDocs Call()
            {
                Debug.Assert(slice.Leaves.Length == 1);
                TopFieldDocs docs = searcher.Search(Arrays.AsList(slice.Leaves), weight, after, nDocs, sort, true, doDocScores || sort.NeedsScores, doMaxScore);

                @lock.Lock();
                try
                {
                    AtomicReaderContext ctx = slice.Leaves[0];
                    int @base = ctx.DocBase;
                    hq.SetNextReader(ctx);
                    hq.SetScorer(fakeScorer);
                    foreach (ScoreDoc scoreDoc in docs.ScoreDocs)
                    {
                        fakeScorer.doc   = scoreDoc.Doc - @base;
                        fakeScorer.score = scoreDoc.Score;
                        hq.Collect(scoreDoc.Doc - @base);
                    }

                    // Carry over maxScore from sub:
                    if (doMaxScore && docs.MaxScore > hq.maxScore)
                    {
                        hq.maxScore = docs.MaxScore;
                    }
                }
                finally
                {
                    @lock.Unlock();
                }
                return(docs);
            }
Esempio n. 16
0
            private void Run()
            {
                if (!IsAlive)
                {
                    SignalStop();
                    return;
                }

                Stopwatch timer = Stopwatch.StartNew();
                @lock.Lock();
                try
                {
                    doUpdate();
                }
                catch (Exception exception)
                {
                    handleException(exception);
                }
                finally
                {
                    @lock.Unlock();

                    timer.Stop();
                    long driftAdjusted = Math.Max(interval - timer.ElapsedMilliseconds, 0);
                    if (IsAlive)
                        RegisterWait(driftAdjusted);
                    else
                        SignalStop();
                }
            }
        /// <summary>
        /// Synchronously acquire access token, must be called in non-main thread
        /// </summary>
        /// <returns>accessToken or null</returns>
        public string RefreshAccessToken()
        {
            Log.Logger.Info(Tag, "refreshAccessToken begin");
            try
            {
                if (service != null)
                {
                    getATLock.Lock();
                    try
                    {
                        GetAccessToken();
                    }
                    finally
                    {
                        getATLock.Unlock();
                    }
                    Log.Logger.Debug(Tag, "refreshAccessToken return new");
                }
                else
                {
                    Log.Logger.Error(Tag, "refreshAccessToken client is null, return null");
                }
            }
            catch (Exception e)
            {
                Log.Logger.Error(Tag, "refreshAccessToken exception, return null");
            }

            Log.Logger.Info(Tag, "refreshAccessToken end");
            return(accessToken);
        }
Esempio n. 18
0
        private void DoMaybeRefresh()
        {
            // it's ok to call lock() here (blocking) because we're supposed to get here
            // from either maybeRefreh() or maybeRefreshBlocking(), after the lock has
            // already been obtained. Doing that protects us from an accidental bug
            // where this method will be called outside the scope of refreshLock.
            // Per ReentrantLock's javadoc, calling lock() by the same thread more than
            // once is ok, as long as unlock() is called a matching number of times.
            refreshLock.Lock();
            bool refreshed = false;

            try
            {
                G reference = Acquire();
                try
                {
                    NotifyRefreshListenersBefore();
                    G newReference = RefreshIfNeeded(reference);
                    if (newReference != null)
                    {
                        Debug.Assert((object)newReference != (object)reference, "refreshIfNeeded should return null if refresh wasn't needed");
                        try
                        {
                            SwapReference(newReference);
                            refreshed = true;
                        }
                        finally
                        {
                            if (!refreshed)
                            {
                                Release(newReference);
                            }
                        }
                    }
                }
                finally
                {
                    Release(reference);
                    NotifyRefreshListenersRefreshed(refreshed);
                }
                AfterMaybeRefresh();
            }
            finally
            {
                refreshLock.Unlock();
            }
        }
Esempio n. 19
0
 public void Start()
 {
     lifecycleLock.Lock();
     try {
         if (!running)
         {
             DoStart();
             running = true;
             if (logger.IsInfoEnabled)
             {
                 logger.Info("started " + this);
             }
         }
     }
     finally {
         lifecycleLock.Unlock();
     }
 }
Esempio n. 20
0
        /**
         * Retrieves and removes the head of this queue, waiting
         * if necessary up to the specified wait time, for another thread
         * to insert it.
         *
         * @return the head of this queue, or <tt>null</tt> if the
         *         specified waiting time elapses before an element is present.
         * @throws InterruptedException {@inheritDoc}
         */
        public override bool Poll(TimeSpan timeout, out T element)
        {
            long          nanos = timeout.Ticks; // unit.toNanos(timeout);
            ReentrantLock qlock = _qlock;

            for (; ;)
            {
                Node node;
                bool mustWait;

                //if (Thread.interrupted()) throw new InterruptedException();
                qlock.Lock();
                try
                {
                    node     = _waitingProducers.Dequeue();
                    mustWait = (node == null);
                    if (mustWait)
                    {
                        node = _waitingConsumers.Enqueue(default(T));
                    }
                }
                finally
                {
                    qlock.Unlock();
                }

                if (mustWait)
                {
                    try
                    {
                        T x;
                        if (!node.WaitForPut(nanos, out x))
                        {
                            UnlinkCancelledConsumer(node);
                        }
                        element = x;
                        return(true);
                    }
                    catch (ThreadInterruptedException)
                    {
                        UnlinkCancelledConsumer(node);
                        throw;
                    }
                }
                else
                {
                    T x;
                    if (node.GetItem(out x))
                    {
                        element = x;
                        return(true);
                    }
                    // else cancelled, so retry
                }
            }
        }
Esempio n. 21
0
        /**
         * Inserts the specified element into this queue, waiting if necessary
         * up to the specified wait time for another thread to receive it.
         *
         * @return <tt>true</tt> if successful, or <tt>false</tt> if the
         *         specified waiting time elapses before a consumer appears.
         * @throws InterruptedException {@inheritDoc}
         * @throws NullPointerException {@inheritDoc}
         */
        public override bool Offer(T e, TimeSpan timeout)
        {
            if (e == null)
            {
                throw new ArgumentNullException();
            }
            long          nanos = DateTime.Now.Ticks;// unit.toNanos(timeout);
            ReentrantLock qlock = _qlock;

            for (; ;)
            {
                Node node;
                bool mustWait;
                //if (Thread.interrupted()) throw new InterruptedException();
                qlock.Lock();
                try
                {
                    node     = _waitingConsumers.Dequeue();
                    mustWait = (node == null);
                    if (mustWait)
                    {
                        node = _waitingProducers.Enqueue(e);
                    }
                }
                finally
                {
                    qlock.Unlock();
                }

                if (mustWait)
                {
                    try
                    {
                        bool x = node.WaitForTake(nanos);
                        if (!x)
                        {
                            UnlinkCancelledProducer(node);
                        }
                        return(x);
                    }
                    catch (ThreadInterruptedException)
                    {
                        UnlinkCancelledProducer(node);
                        throw;
                    }
                }

                if (node.SetItem(e))
                {
                    return(true);
                }

                // else consumer cancelled, so retry
            }
        }
Esempio n. 22
0
        /// <summary>
        /// Atomically removes all of the elements from this queue.
        /// The queue will be empty after this call returns.
        /// </summary>
        public override void Clear()
        {
            ReentrantLock rl = _lock;

            rl.Lock();
            try {
                _innerQueue.Clear();
            }
            finally {
                rl.Unlock();
            }
        }
Esempio n. 23
0
 // Configuration Keys
 /* The queues */
 /* Read locks */
 private void SignalNotEmpty()
 {
     takeLock.Lock();
     try
     {
         notEmpty.Signal();
     }
     finally
     {
         takeLock.Unlock();
     }
 }
Esempio n. 24
0
        /// <summary>
        /// get the string representation of the queue
        /// </summary>
        /// <returns>the string representation of the queue</returns>
        public override string ToString()
        {
            ReentrantLock rl = _lock;

            rl.Lock();
            try {
                return(_innerQueue.ToString());
            }
            finally {
                rl.Unlock();
            }
        }
Esempio n. 25
0
 /**
  * Unlinks the given node from consumer queue.  Called by cancelled
  * (timeout, interrupt) waiters to avoid garbage retention in the
  * absence of producers.
  */
 private void UnlinkCancelledConsumer(Node node)
 {
     // Use a form of double-check to avoid unnecessary locking and
     // traversal. The first check outside lock might
     // conservatively report true.
     if (_waitingConsumers.ShouldUnlink(node))
     {
         _qlock.Lock();
         try
         {
             if (_waitingConsumers.ShouldUnlink(node))
             {
                 _waitingConsumers.Unlink(node);
             }
         }
         finally
         {
             _qlock.Unlock();
         }
     }
 }
Esempio n. 26
0
        /// <summary>
        /// Returns {@code true} if this queue contains the specified element.
        /// More formally, returns {@code true} if and only if this queue contains
        /// at least one element {@code e} such that {@code o.equals(e)}.
        /// </summary>
        /// <param name="element">element to be checked for containment in this queue</param>
        /// <returns><tt>true</tt> if this queue contains the specified element</returns>
        public override bool Contains(T element)
        {
            ReentrantLock rl = _lock;

            rl.Lock();
            try {
                return(_innerQueue.Contains(element));
            }
            finally {
                rl.Unlock();
            }
        }
Esempio n. 27
0
 public override bool IsCancelled()
 {
     Lock.Lock();
     try
     {
         return(pm.IsCancelled());
     }
     finally
     {
         Lock.Unlock();
     }
 }
Esempio n. 28
0
 public void HandleDataDeleted(string dataPath)
 {
     dataLock.Lock();
     try
     {
         dataExistsOrChanged.Signal();
     }
     finally
     {
         dataLock.Unlock();
     }
 }
Esempio n. 29
0
        /// <summary>
        /// Retrieves, but does not remove, the head of this queue into out
        /// parameter <paramref name="element"/>.
        /// </summary>
        /// <param name="element">
        /// The head of this queue. <c>default(T)</c> if queue is empty.
        /// </param>
        /// <returns>
        /// <c>false</c> is the queue is empty. Otherwise <c>true</c>.
        /// </returns>
        public override bool Peek(out T element)
        {
            ReentrantLock rl = _lock;

            rl.Lock();
            try {
                return(_innerQueue.Peek(out element));
            }
            finally {
                rl.Unlock();
            }
        }
        public virtual int AddToIndex(E o)
        {
            int index = item2Index[o];

            if (index != null)
            {
                return(index);
            }
            Lock.Lock();
            try
            {
                // Recheck state
                if (item2Index.Contains(o))
                {
                    return(item2Index[o]);
                }
                else
                {
                    int      newIndex = indexSize++;
                    object[] arr      = index2Item.Get();
                    System.Diagnostics.Debug.Assert(newIndex <= arr.Length);
                    if (newIndex == arr.Length)
                    {
                        // Increase size of array if necessary
                        object[] newArr = new object[2 * newIndex];
                        System.Array.Copy(arr, 0, newArr, 0, arr.Length);
                        arr = newArr;
                    }
                    arr[newIndex] = o;
                    index2Item.Set(arr);
                    item2Index[o] = newIndex;
                    return(newIndex);
                }
            }
            finally
            {
                Lock.Unlock();
            }
        }