Пример #1
0
        /// <summary>
        /// Test that when access time updates are not needed, the FSNamesystem
        /// write lock is not taken by getBlockLocations.
        /// </summary>
        /// <remarks>
        /// Test that when access time updates are not needed, the FSNamesystem
        /// write lock is not taken by getBlockLocations.
        /// Regression test for HDFS-3981.
        /// </remarks>
        /// <exception cref="System.IO.IOException"/>
        public virtual void TestGetBlockLocationsOnlyUsesReadLock()
        {
            Configuration conf = new HdfsConfiguration();

            conf.SetInt(DFSConfigKeys.DfsNamenodeAccesstimePrecisionKey, 100 * 1000);
            MiniDFSCluster         cluster = new MiniDFSCluster.Builder(conf).NumDataNodes(0).Build();
            ReentrantReadWriteLock spyLock = NameNodeAdapter.SpyOnFsLock(cluster.GetNamesystem
                                                                             ());

            try
            {
                // Create empty file in the FSN.
                Path p = new Path("/empty-file");
                DFSTestUtil.CreateFile(cluster.GetFileSystem(), p, 0, (short)1, 0L);
                // getBlockLocations() should not need the write lock, since we just created
                // the file (and thus its access time is already within the 100-second
                // accesstime precision configured above).
                MockitoUtil.DoThrowWhenCallStackMatches(new Exception("Should not need write lock"
                                                                      ), ".*getBlockLocations.*").When(spyLock).WriteLock();
                cluster.GetFileSystem().GetFileBlockLocations(p, 0, 100);
            }
            finally
            {
                cluster.Shutdown();
            }
        }
Пример #2
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldRetainLockWhileStreaming() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldRetainLockWhileStreaming()
        {
            // given
            ChannelPromise        channelPromise        = _embeddedChannel.newPromise();
            ChannelHandlerContext channelHandlerContext = mock(typeof(ChannelHandlerContext));

            when(channelHandlerContext.writeAndFlush(any(typeof(PrepareStoreCopyResponse)))).thenReturn(channelPromise);

            ReentrantReadWriteLock @lock = new ReentrantReadWriteLock();

            when(_neoStoreDataSource.StoreCopyCheckPointMutex).thenReturn(new StoreCopyCheckPointMutex(@lock));
            PrepareStoreCopyRequestHandler subjectHandler = CreateHandler();

            // and
            LongSet indexIds = LongSets.immutable.of(42);

            File[] files          = new File[] { new File("file") };
            long   lastCheckpoint = 1;

            ConfigureProvidedStoreCopyFiles(new StoreResource[0], files, indexIds, lastCheckpoint);

            // when
            subjectHandler.ChannelRead0(channelHandlerContext, new PrepareStoreCopyRequest(_storeIdMatching));

            // then
            assertEquals(1, @lock.ReadLockCount);

            // when
            channelPromise.setSuccess();

            //then
            assertEquals(0, @lock.ReadLockCount);
        }
Пример #3
0
        /// <summary>
        /// Regression test for HDFS-2693: when doing state transitions, we need to
        /// lock the FSNamesystem so that we don't end up doing any writes while it's
        /// "in between" states.
        /// </summary>
        /// <remarks>
        /// Regression test for HDFS-2693: when doing state transitions, we need to
        /// lock the FSNamesystem so that we don't end up doing any writes while it's
        /// "in between" states.
        /// This test case starts up several client threads which do mutation operations
        /// while flipping a NN back and forth from active to standby.
        /// </remarks>
        /// <exception cref="System.Exception"/>
        public virtual void TestTransitionSynchronization()
        {
            Configuration  conf    = new Configuration();
            MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).NnTopology(MiniDFSNNTopology
                                                                                 .SimpleHATopology()).NumDataNodes(0).Build();

            try
            {
                cluster.WaitActive();
                ReentrantReadWriteLock spyLock = NameNodeAdapter.SpyOnFsLock(cluster.GetNameNode(
                                                                                 0).GetNamesystem());
                Org.Mockito.Mockito.DoAnswer(new GenericTestUtils.SleepAnswer(50)).When(spyLock).
                WriteLock();
                FileSystem fs = HATestUtil.ConfigureFailoverFs(cluster, conf);
                MultithreadedTestUtil.TestContext ctx = new MultithreadedTestUtil.TestContext();
                for (int i = 0; i < 50; i++)
                {
                    int finalI = i;
                    ctx.AddThread(new _RepeatingTestThread_256(finalI, fs, ctx));
                }
                ctx.AddThread(new _RepeatingTestThread_266(cluster, ctx));
                ctx.StartThreads();
                ctx.WaitFor(20000);
                ctx.Stop();
            }
            finally
            {
                cluster.Shutdown();
            }
        }
Пример #4
0
        public static ReentrantReadWriteLock SpyOnFsLock(FSNamesystem fsn)
        {
            ReentrantReadWriteLock spy = Org.Mockito.Mockito.Spy(fsn.GetFsLockForTests());

            fsn.SetFsLockForTests(spy);
            return(spy);
        }
        public CommonNodeLabelsManager()
            : base(typeof(CommonNodeLabelsManager).FullName)
        {
            ReentrantReadWriteLock Lock = new ReentrantReadWriteLock();

            readLock  = Lock.ReadLock();
            writeLock = Lock.WriteLock();
        }
Пример #6
0
        public QueueCapacities(bool isRoot)
        {
            ReentrantReadWriteLock Lock = new ReentrantReadWriteLock();

            readLock      = Lock.ReadLock();
            writeLock     = Lock.WriteLock();
            capacitiesMap = new Dictionary <string, QueueCapacities.Capacities>();
            this.isRoot   = isRoot;
        }
Пример #7
0
        public ResourceUsage()
        {
            // short for no-label :)
            ReentrantReadWriteLock Lock = new ReentrantReadWriteLock();

            readLock   = Lock.ReadLock();
            writeLock  = Lock.WriteLock();
            usages     = new Dictionary <string, ResourceUsage.UsageByLabel>();
            usages[Nl] = new ResourceUsage.UsageByLabel(Nl);
        }
Пример #8
0
            public StatefulContainer(NMClientAsync client, ContainerId containerId)
            {
                this.nmClientAsync = client;
                this.containerId   = containerId;
                stateMachine       = stateMachineFactory.Make(this);
                ReentrantReadWriteLock Lock = new ReentrantReadWriteLock();

                readLock  = Lock.ReadLock();
                writeLock = Lock.WriteLock();
            }
Пример #9
0
        /// <summary>
        /// The constructor takes a
        /// <see cref="Org.Apache.Hadoop.Crypto.Key.KeyProviderCryptoExtension"/>
        /// and an
        /// implementation of <code>KeyACLs</code>. All calls are delegated to the
        /// provider keyProvider after authorization check (if required)
        /// </summary>
        /// <param name="keyProvider"></param>
        /// <param name="acls"/>
        public KeyAuthorizationKeyProvider(KeyProviderCryptoExtension keyProvider, KeyAuthorizationKeyProvider.KeyACLs
                                           acls)
            : base(keyProvider, null)
        {
            this.provider = keyProvider;
            this.acls     = acls;
            ReadWriteLock Lock = new ReentrantReadWriteLock(true);

            readLock  = Lock.ReadLock();
            writeLock = Lock.WriteLock();
        }
 public void TestConstructor()
 {
     ReentrantReadWriteLock rl = new ReentrantReadWriteLock();
     Assert.IsFalse(rl.IsFair);
     Assert.IsFalse(rl.IsWriteLocked);
     Assert.AreEqual(0, rl.ReadLockCount);
     ReentrantReadWriteLock r2 = new ReentrantReadWriteLock(true);
     Assert.IsTrue(r2.IsFair);
     Assert.IsFalse(r2.IsWriteLocked);
     Assert.AreEqual(0, r2.ReadLockCount);
 }
Пример #11
0
        public RMAppAttemptMetrics(ApplicationAttemptId attemptId, RMContext rmContext)
        {
            // preemption info
            // application headroom
            //HM: Line below replaced by one above for issue wih array 2nd dim
            //new int[NodeType.values().length][NodeType.values().length];
            this.attemptId = attemptId;
            ReentrantReadWriteLock Lock = new ReentrantReadWriteLock();

            this.readLock  = Lock.ReadLock();
            this.writeLock = Lock.WriteLock();
            this.rmContext = rmContext;
        }
Пример #12
0
        /// <summary>Construct the service.</summary>
        /// <param name="name">service name</param>
        public AbstractYarnScheduler(string name)
            : base(name)
        {
            // Nodes in the cluster, indexed by NodeId
            // Whole capacity of the cluster

            /*
             * All schedulers which are inheriting AbstractYarnScheduler should use
             * concurrent version of 'applications' map.
             */
            ReentrantReadWriteLock Lock = new ReentrantReadWriteLock();

            this.maxAllocReadLock  = Lock.ReadLock();
            this.maxAllocWriteLock = Lock.WriteLock();
        }
Пример #13
0
        public ApplicationImpl(Dispatcher dispatcher, string user, ApplicationId appId, Credentials
                               credentials, Context context)
        {
            this.dispatcher  = dispatcher;
            this.user        = user;
            this.appId       = appId;
            this.credentials = credentials;
            this.aclsManager = context.GetApplicationACLsManager();
            this.context     = context;
            ReentrantReadWriteLock Lock = new ReentrantReadWriteLock();

            readLock     = Lock.ReadLock();
            writeLock    = Lock.WriteLock();
            stateMachine = stateMachineFactory.Make(this);
        }
Пример #14
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void stressIt() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void StressIt()
        {
            Race race = new Race();
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.concurrent.atomic.AtomicReferenceArray<java.util.List<? extends org.neo4j.kernel.api.index.IndexEntryUpdate<?>>> lastBatches = new java.util.concurrent.atomic.AtomicReferenceArray<>(THREADS);
            AtomicReferenceArray <IList <IndexEntryUpdate <object> > > lastBatches = new AtomicReferenceArray <IList <IndexEntryUpdate <object> > >(THREADS);

            Generator[] generators = new Generator[THREADS];

            _populator.create();
            System.Threading.CountdownEvent insertersDone = new System.Threading.CountdownEvent(THREADS);
            ReadWriteLock updateLock = new ReentrantReadWriteLock(true);

            for (int i = 0; i < THREADS; i++)
            {
                race.AddContestant(Inserter(lastBatches, generators, insertersDone, updateLock, i), 1);
            }
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.Collection<org.neo4j.kernel.api.index.IndexEntryUpdate<?>> updates = new java.util.ArrayList<>();
            ICollection <IndexEntryUpdate <object> > updates = new List <IndexEntryUpdate <object> >();

            race.AddContestant(Updater(lastBatches, insertersDone, updateLock, updates));

            race.Go();
            _populator.close(true);
            _populator = null;               // to let the after-method know that we've closed it ourselves

            // then assert that a tree built by a single thread ends up exactly the same
            BuildReferencePopulatorSingleThreaded(generators, updates);
            using (IndexAccessor accessor = _indexProvider.getOnlineAccessor(Descriptor, _samplingConfig), IndexAccessor referenceAccessor = _indexProvider.getOnlineAccessor(_descriptor2, _samplingConfig), IndexReader reader = accessor.NewReader(), IndexReader referenceReader = referenceAccessor.NewReader())
            {
                SimpleNodeValueClient entries          = new SimpleNodeValueClient();
                SimpleNodeValueClient referenceEntries = new SimpleNodeValueClient();
                reader.Query(entries, IndexOrder.NONE, HasValues, IndexQuery.exists(0));
                referenceReader.Query(referenceEntries, IndexOrder.NONE, HasValues, IndexQuery.exists(0));
                while (referenceEntries.Next())
                {
                    assertTrue(entries.Next());
                    assertEquals(referenceEntries.Reference, entries.Reference);
                    if (HasValues)
                    {
                        assertEquals(ValueTuple.of(referenceEntries.Values), ValueTuple.of(entries.Values));
                    }
                }
                assertFalse(entries.Next());
            }
        }
Пример #15
0
        public LocalizedResource(LocalResourceRequest rsrc, Dispatcher dispatcher)
        {
            timestamp = new AtomicLong(CurrentTime());
            // Queue of containers using this localized
            // resource
            // From INIT (ref == 0, awaiting req)
            // From DOWNLOADING (ref > 0, may be localizing)
            // TODO: Duplicate addition!!
            // From LOCALIZED (ref >= 0, on disk)
            this.rsrc       = rsrc;
            this.dispatcher = dispatcher;
            this.@ref       = new List <ContainerId>();
            ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

            this.readLock     = readWriteLock.ReadLock();
            this.writeLock    = readWriteLock.WriteLock();
            this.stateMachine = stateMachineFactory.Make(this);
        }
Пример #16
0
        public RMContainerImpl(Container container, ApplicationAttemptId appAttemptId, NodeId
                               nodeId, string user, RMContext rmContext, long creationTime)
        {
            // Transitions from NEW state
            // Transitions from RESERVED state
            // nothing to do
            // nothing to do
            // Transitions from ALLOCATED state
            // Transitions from ACQUIRED state
            // Transitions from RUNNING state
            // Transitions from COMPLETED state
            // Transitions from EXPIRED state
            // Transitions from RELEASED state
            // Transitions from KILLED state
            // create the topology tables
            this.stateMachine = stateMachineFactory.Make(this);
            this.containerId  = container.GetId();
            this.nodeId       = nodeId;
            this.container    = container;
            this.appAttemptId = appAttemptId;
            this.user         = user;
            this.creationTime = creationTime;
            this.rmContext    = rmContext;
            this.eventHandler = rmContext.GetDispatcher().GetEventHandler();
            this.containerAllocationExpirer = rmContext.GetContainerAllocationExpirer();
            this.isAMContainer    = false;
            this.resourceRequests = null;
            ReentrantReadWriteLock Lock = new ReentrantReadWriteLock();

            this.readLock              = Lock.ReadLock();
            this.writeLock             = Lock.WriteLock();
            saveNonAMContainerMetaInfo = rmContext.GetYarnConfiguration().GetBoolean(YarnConfiguration
                                                                                     .ApplicationHistorySaveNonAmContainerMetaInfo, YarnConfiguration.DefaultApplicationHistorySaveNonAmContainerMetaInfo
                                                                                     );
            rmContext.GetRMApplicationHistoryWriter().ContainerStarted(this);
            // If saveNonAMContainerMetaInfo is true, store system metrics for all
            // containers. If false, and if this container is marked as the AM, metrics
            // will still be published for this container, but that calculation happens
            // later.
            if (saveNonAMContainerMetaInfo)
            {
                rmContext.GetSystemMetricsPublisher().ContainerCreated(this, this.creationTime);
            }
        }
 /// <summary>
 /// Creates a new FileSystemTileCache.
 /// <para>
 /// Use the {@code persistent} argument to specify whether cache contents should be kept across instances. A
 /// persistent cache will serve any tiles it finds in {@code cacheDirectory}. Calling <seealso cref="#destroy()"/> on a
 /// persistent cache will not delete the cache directory. Conversely, a non-persistent cache will serve only tiles
 /// added to it via the <seealso cref="#put(Job, TileBitmap)"/> method, and calling <seealso cref="#destroy()"/> on a non-persistent
 /// cache will delete {@code cacheDirectory}.
 ///
 /// </para>
 /// </summary>
 /// <param name="capacity">
 ///            the maximum number of entries in this cache. </param>
 /// <param name="cacheDirectory">
 ///            the directory where cached tiles will be stored. </param>
 /// <param name="graphicFactory">
 ///            the graphicFactory implementation to use. </param>
 /// <param name="persistent">
 ///            if cache data will be kept between instances </param>
 /// <exception cref="IllegalArgumentException">
 ///             if the capacity is negative. </exception>
 /// <exception cref="IllegalArgumentException">
 ///             if the capacity is negative. </exception>
 public FileSystemTileCache(int capacity, IFolder cacheDirectory, IGraphicFactory graphicFactory, bool persistent)
 {
     this.observable = new Observable();
     this.persistent = persistent;
     this.lruCache   = new FileWorkingSetCache <string>(capacity);
     this.@lock      = new ReentrantReadWriteLock();
     if (IsValidCacheDirectory(cacheDirectory))
     {
         this.cacheDirectory = cacheDirectory;
         if (this.persistent)
         {
             // this will start a new thread to read in the cache directory.
             // there is the potential that files will be recreated because they
             // are not yet in the cache, but this will not cause any corruption.
             Task.Run(() => (new CacheDirectoryReader(this)).Run());
         }
     }
     else
     {
         this.cacheDirectory = null;
     }
     this.graphicFactory = graphicFactory;
 }
        public void TestReadLockInterruptibly()
        {
            ReentrantReadWriteLock locker = new ReentrantReadWriteLock();
            try
            {
                locker.WriteLock.LockInterruptibly();
            }
            catch(Exception e)
            {
                UnexpectedException(e);
            }
            Thread t = new Thread(TestReadLockInterruptiblyRun);

            try
            {
                t.Start(locker);
                Thread.Sleep(SHORT_DELAY_MS);
                t.Interrupt();
                t.Join();
                locker.WriteLock.UnLock();
            }
            catch(Exception e)
            {
                UnexpectedException(e);
            }
        }
 public void TestLock()
 {
     ReentrantReadWriteLock rl = new ReentrantReadWriteLock();
     rl.WriteLock.Lock();
     Assert.IsTrue(rl.IsWriteLocked);
     Assert.IsTrue(rl.IsWriteLockedByCurrentThread);
     Assert.AreEqual(0, rl.ReadLockCount);
     rl.WriteLock.UnLock();
     Assert.IsFalse(rl.IsWriteLocked);
     Assert.IsFalse(rl.IsWriteLockedByCurrentThread);
     Assert.AreEqual(0, rl.ReadLockCount);
     rl.ReadLock.Lock();
     Assert.IsFalse(rl.IsWriteLocked);
     Assert.IsFalse(rl.IsWriteLockedByCurrentThread);
     Assert.AreEqual(1, rl.ReadLockCount);
     rl.ReadLock.UnLock();
     Assert.IsFalse(rl.IsWriteLocked);
     Assert.IsFalse(rl.IsWriteLockedByCurrentThread);
     Assert.AreEqual(0, rl.ReadLockCount);
 }
 public void TestHasWaitersAE()
 {
     ReentrantReadWriteLock locker = new ReentrantReadWriteLock();
     Condition c = (locker.WriteLock.NewCondition());
     ReentrantReadWriteLock locker2 = new ReentrantReadWriteLock();
     try
     {
         locker2.HasWaiters(c);
         ShouldThrow();
     }
     catch (ArgumentException)
     {
     }
     catch (Exception e)
     {
         UnexpectedException(e);
     }
 }
        /// <exception cref="System.IO.IOException"/>
        protected internal AbstractJavaKeyStoreProvider(URI uri, Configuration conf)
        {
            this.uri = uri;
            InitFileSystem(uri, conf);
            // Get the password from the user's environment
            if (Runtime.GetEnv().Contains(CredentialPasswordName))
            {
                password = Runtime.Getenv(CredentialPasswordName).ToCharArray();
            }
            // if not in ENV get check for file
            if (password == null)
            {
                string pwFile = conf.Get(KeystorePasswordFileKey);
                if (pwFile != null)
                {
                    ClassLoader cl      = Thread.CurrentThread().GetContextClassLoader();
                    Uri         pwdFile = cl.GetResource(pwFile);
                    if (pwdFile != null)
                    {
                        using (InputStream @is = pwdFile.OpenStream())
                        {
                            password = IOUtils.ToString(@is).Trim().ToCharArray();
                        }
                    }
                }
            }
            if (password == null)
            {
                password = KeystorePasswordDefault.ToCharArray();
            }
            try
            {
                keyStore = KeyStore.GetInstance("jceks");
                if (KeystoreExists())
                {
                    StashOriginalFilePermissions();
                    using (InputStream @in = GetInputStreamForFile())
                    {
                        keyStore.Load(@in, password);
                    }
                }
                else
                {
                    CreatePermissions("700");
                    // required to create an empty keystore. *sigh*
                    keyStore.Load(null, password);
                }
            }
            catch (KeyStoreException e)
            {
                throw new IOException("Can't create keystore", e);
            }
            catch (NoSuchAlgorithmException e)
            {
                throw new IOException("Can't load keystore " + GetPathAsString(), e);
            }
            catch (CertificateException e)
            {
                throw new IOException("Can't load keystore " + GetPathAsString(), e);
            }
            ReadWriteLock Lock = new ReentrantReadWriteLock(true);

            readLock  = Lock.ReadLock();
            writeLock = Lock.WriteLock();
        }
Пример #22
0
        /// <exception cref="System.IO.IOException"/>
        private JavaKeyStoreProvider(URI uri, Configuration conf)
            : base(conf)
        {
            this.uri = uri;
            path     = ProviderUtils.UnnestUri(uri);
            fs       = path.GetFileSystem(conf);
            // Get the password file from the conf, if not present from the user's
            // environment var
            if (Runtime.GetEnv().Contains(KeystorePasswordEnvVar))
            {
                password = Runtime.Getenv(KeystorePasswordEnvVar).ToCharArray();
            }
            if (password == null)
            {
                string pwFile = conf.Get(KeystorePasswordFileKey);
                if (pwFile != null)
                {
                    ClassLoader cl      = Thread.CurrentThread().GetContextClassLoader();
                    Uri         pwdFile = cl.GetResource(pwFile);
                    if (pwdFile == null)
                    {
                        // Provided Password file does not exist
                        throw new IOException("Password file does not exists");
                    }
                    using (InputStream @is = pwdFile.OpenStream())
                    {
                        password = IOUtils.ToString(@is).Trim().ToCharArray();
                    }
                }
            }
            if (password == null)
            {
                password = KeystorePasswordDefault;
            }
            try
            {
                Path oldPath = ConstructOldPath(path);
                Path newPath = ConstructNewPath(path);
                keyStore = KeyStore.GetInstance(SchemeName);
                FsPermission perm = null;
                if (fs.Exists(path))
                {
                    // flush did not proceed to completion
                    // _NEW should not exist
                    if (fs.Exists(newPath))
                    {
                        throw new IOException(string.Format("Keystore not loaded due to some inconsistency "
                                                            + "('%s' and '%s' should not exist together)!!", path, newPath));
                    }
                    perm = TryLoadFromPath(path, oldPath);
                }
                else
                {
                    perm = TryLoadIncompleteFlush(oldPath, newPath);
                }
                // Need to save off permissions in case we need to
                // rewrite the keystore in flush()
                permissions = perm;
            }
            catch (KeyStoreException e)
            {
                throw new IOException("Can't create keystore", e);
            }
            catch (NoSuchAlgorithmException e)
            {
                throw new IOException("Can't load keystore " + path, e);
            }
            catch (CertificateException e)
            {
                throw new IOException("Can't load keystore " + path, e);
            }
            ReadWriteLock Lock = new ReentrantReadWriteLock(true);

            readLock  = Lock.ReadLock();
            writeLock = Lock.WriteLock();
        }
 public void TestUnlockThreadStateException()
 {
     ReentrantReadWriteLock rl = new ReentrantReadWriteLock();
     try
     {
         rl.WriteLock.UnLock();
         ShouldThrow();
     }
     catch(ThreadStateException)
     {
     }
 }
 public void TestAwaitNanosTimeout()
 {
     ReentrantReadWriteLock locker = new ReentrantReadWriteLock();
     Condition c = locker.WriteLock.NewCondition();
     try
     {
         locker.WriteLock.Lock();
         long t = c.Await(100);
         Assert.IsTrue(t <= 0);
         locker.WriteLock.UnLock();
     }
     catch (Exception e)
     {
         UnexpectedException(e);
     }
 }
 public void TestGetWriteHoldCount()
 {
     ReentrantReadWriteLock locker = new ReentrantReadWriteLock();
     for(int i = 1; i <= SIZE; i++)
     {
         locker.WriteLock.Lock();
         Assert.AreEqual(i, locker.WriteHoldCount);
     }
     for(int i = SIZE; i > 0; i--)
     {
         locker.WriteLock.UnLock();
         Assert.AreEqual(i-1, locker.WriteHoldCount);
     }
 }
        public void TestMultipleReadLocks()
        {
            ReentrantReadWriteLock locker = new ReentrantReadWriteLock();
            locker.ReadLock.Lock();
            Thread t = new Thread(TestMultipleReadLocksRun);

            try
            {
                t.Start(locker);
                t.Join();
                locker.ReadLock.UnLock();
            }
            catch(Exception e)
            {
                UnexpectedException(e);
            }
        }
 public void TestWriteLockToString()
 {
     ReentrantReadWriteLock locker = new ReentrantReadWriteLock();
     String us = locker.WriteLock.ToString();
     Assert.IsTrue(us.IndexOf("Unlocked") >= 0);
     locker.WriteLock.Lock();
     String ls = locker.WriteLock.ToString();
     Assert.IsTrue(ls.IndexOf("Locked") >= 0);
 }
 public void TestReadLockToString()
 {
     ReentrantReadWriteLock locker = new ReentrantReadWriteLock();
     String us = locker.ReadLock.ToString();
     Assert.IsTrue(us.IndexOf("Read locks = 0") >= 0);
     locker.ReadLock.Lock();
     locker.ReadLock.Lock();
     String rs = locker.ReadLock.ToString();
     Assert.IsTrue(rs.IndexOf("Read locks = 2") >= 0);
 }
     public void TestGetWaitQueueLength()
     {
         ReentrantReadWriteLock locker = new ReentrantReadWriteLock();
         Condition c = (locker.WriteLock.NewCondition());
         Pair data = new Pair(locker, c);
         Thread t = new Thread(TestGetWaitQueueLengthRun);
 
         try
         {
             t.Start(data);
             Thread.Sleep(SHORT_DELAY_MS);
             locker.WriteLock.Lock();
             Assert.IsTrue(locker.HasWaiters(c));
             Assert.AreEqual(1, locker.GetWaitQueueLength(c));
             c.Signal();
             locker.WriteLock.UnLock();
             Thread.Sleep(SHORT_DELAY_MS);
             locker.WriteLock.Lock();
             Assert.IsFalse(locker.HasWaiters(c));
             Assert.AreEqual(0, locker.GetWaitQueueLength(c));
             locker.WriteLock.UnLock();
             t.Join(SHORT_DELAY_MS);
             Assert.IsFalse(t.IsAlive);
         }
         catch (Exception e)
         {
             UnexpectedException(e);
         }
     }
 public void TestGetWaitQueueLengthTSE()
 {
     ReentrantReadWriteLock locker = new ReentrantReadWriteLock();
     Condition c = (locker.WriteLock.NewCondition());
     try
     {
         locker.GetWaitQueueLength(c);
         ShouldThrow();
     }
     catch (ThreadStateException)
     {
     }
     catch (Exception e)
     {
         UnexpectedException(e);
     }
 }
 public void TestAwaitThreadStateException()
 {
     ReentrantReadWriteLock locker = new ReentrantReadWriteLock();
     Condition c = locker.WriteLock.NewCondition();
     try
     {
         c.Await();
         ShouldThrow();
     }
     catch (ThreadStateException)
     {
     }
     catch (Exception)
     {
         ShouldThrow();
     }
 }
 public void TestSignalThreadStateException()
 {
     ReentrantReadWriteLock locker = new ReentrantReadWriteLock();
     Condition c = locker.WriteLock.NewCondition();
     try
     {
         c.Signal();
         ShouldThrow();
     }
     catch (ThreadStateException)
     {
     }
     catch (Exception e)
     {
         UnexpectedException(e);
     }
 }
 public void TestReadHoldingWriteLockFair()
 {
     ReentrantReadWriteLock locker = new ReentrantReadWriteLock(true);
     locker.WriteLock.Lock();
     Assert.IsTrue(locker.ReadLock.TryLock());
     locker.ReadLock.UnLock();
     locker.WriteLock.UnLock();
 }
 public void TestAwaitTimeout()
 {
     ReentrantReadWriteLock locker = new ReentrantReadWriteLock();
     Condition c = locker.WriteLock.NewCondition();
     try
     {
         locker.WriteLock.Lock();
         c.Await(150);
         locker.WriteLock.UnLock();
     }
     catch (Exception e)
     {
         UnexpectedException(e);
     }
 }
     public void TestWriteHoldingWriteLockFair4()
     {
         ReentrantReadWriteLock locker = new ReentrantReadWriteLock(true);
         locker.WriteLock.Lock();
         Thread t1 = new Thread(TestWriteHoldingWriteLockFair4Run);
         Thread t2 = new Thread(TestWriteHoldingWriteLockFair4Run);
 
         try
         {
             t1.Start(locker);
             t2.Start(locker);
             Thread.Sleep(SHORT_DELAY_MS);
             Assert.IsTrue(locker.IsWriteLockedByCurrentThread);
             Assert.IsTrue(locker.WriteHoldCount == 1);
             locker.WriteLock.Lock();
             Assert.IsTrue(locker.WriteHoldCount == 2);
             locker.WriteLock.UnLock();
             locker.WriteLock.Lock();
             locker.WriteLock.UnLock();
             locker.WriteLock.UnLock();
             t1.Join(MEDIUM_DELAY_MS);
             t2.Join(MEDIUM_DELAY_MS);
             Assert.IsTrue(!t1.IsAlive);
             Assert.IsTrue(!t2.IsAlive);
         }
         catch(Exception e)
         {
             UnexpectedException(e);
         }
     }
Пример #36
0
 internal FSNamesystemLock(bool fair)
 {
     this.coarseLock = new ReentrantReadWriteLock(fair);
 }
 public void TestHasWaitersNRE()
 {
     ReentrantReadWriteLock locker = new ReentrantReadWriteLock();
     try
     {
         locker.HasWaiters(null);
         ShouldThrow();
     }
     catch (NullReferenceException)
     {
     }
     catch (Exception e)
     {
         UnexpectedException(e);
     }
 }
        public void TestGetQueueLength()
        {
            ReentrantReadWriteLock locker = new ReentrantReadWriteLock();
            Thread t1 = new Thread(InterruptedLockRunnable);
            Thread t2 = new Thread(InterruptibleLockRunnable);

            try
            {
                Assert.AreEqual(0, locker.QueueLength);
                locker.WriteLock.Lock();
                t1.Start(locker);
                Thread.Sleep(SHORT_DELAY_MS);
                Assert.AreEqual(1, locker.QueueLength);
                t2.Start(locker);
                Thread.Sleep(SHORT_DELAY_MS);
                Assert.AreEqual(2, locker.QueueLength);
                t1.Interrupt();
                Thread.Sleep(SHORT_DELAY_MS);
                Assert.AreEqual(1, locker.QueueLength);
                locker.WriteLock.UnLock();
                Thread.Sleep(SHORT_DELAY_MS);
                Assert.AreEqual(0, locker.QueueLength);
                t1.Join();
                t2.Join();
            }
            catch(Exception e)
            {
                UnexpectedException(e);
            }
        }
        public void TestHasQueuedThread()
        {
            ReentrantReadWriteLock sync = new ReentrantReadWriteLock();
            Thread t1 = new Thread(InterruptedLockRunnable);
            Thread t2 = new Thread(InterruptibleLockRunnable);

            try
            {
                Assert.IsFalse(sync.HasQueuedThread(t1));
                Assert.IsFalse(sync.HasQueuedThread(t2));
                sync.WriteLock.Lock();
                t1.Start(sync);
                Thread.Sleep(SHORT_DELAY_MS);
                Assert.IsTrue(sync.HasQueuedThread(t1));
                t2.Start(sync);
                Thread.Sleep(SHORT_DELAY_MS);
                Assert.IsTrue(sync.HasQueuedThread(t1));
                Assert.IsTrue(sync.HasQueuedThread(t2));
                t1.Interrupt();
                Thread.Sleep(SHORT_DELAY_MS);
                Assert.IsFalse(sync.HasQueuedThread(t1));
                Assert.IsTrue(sync.HasQueuedThread(t2));
                sync.WriteLock.UnLock();
                Thread.Sleep(SHORT_DELAY_MS);
                Assert.IsFalse(sync.HasQueuedThread(t1));
                Thread.Sleep(SHORT_DELAY_MS);
                Assert.IsFalse(sync.HasQueuedThread(t2));
                t1.Join();
                t2.Join();
            }
            catch(Exception e)
            {
                UnexpectedException(e);
            }
        }
     public void TestSignalAll()
     {
         ReentrantReadWriteLock locker = new ReentrantReadWriteLock();
         Condition c = locker.WriteLock.NewCondition();
         Pair data = new Pair(locker, c);
         Thread t1 = new Thread(TestSignalAllRun);
         Thread t2 = new Thread(TestSignalAllRun);
 
         try
         {
             t1.Start(data);
             t2.Start(data);
             Thread.Sleep(SHORT_DELAY_MS);
             locker.WriteLock.Lock();
             c.SignalAll();
             locker.WriteLock.UnLock();
             t1.Join(SHORT_DELAY_MS);
             t2.Join(SHORT_DELAY_MS);
             Assert.IsFalse(t1.IsAlive);
             Assert.IsFalse(t2.IsAlive);
         }
         catch (Exception e)
         {
             UnexpectedException(e);
         }
     }
 public void TestGetWaitQueueLengthNRE()
 {
     ReentrantReadWriteLock locker = new ReentrantReadWriteLock();
     try
     {
         locker.GetWaitQueueLength(null);
         ShouldThrow();
     }
     catch (NullReferenceException)
     {
     }
     catch (Exception e)
     {
         UnexpectedException(e);
     }
 }
     public void TestAwaitUntilInterrupt()
     {
         ReentrantReadWriteLock locker = new ReentrantReadWriteLock();
         Condition c = locker.WriteLock.NewCondition();
         Pair data = new Pair(locker, c);
         Thread t = new Thread(TestAwaitUntilInterruptRun);
 
         try
         {
             t.Start(data);
             Thread.Sleep(SHORT_DELAY_MS);
             t.Interrupt();
             t.Join(SHORT_DELAY_MS);
             Assert.IsFalse(t.IsAlive);
         }
         catch (Exception e)
         {
             UnexpectedException(e);
         }
     }
        public void TestReadTryLockTimeout()
        {
            ReentrantReadWriteLock locker = new ReentrantReadWriteLock();
            locker.WriteLock.Lock();
            Thread t = new Thread(TestReadTryLockTimeoutRun);

            try
            {
                t.Start(locker);
                t.Join();
                locker.WriteLock.UnLock();
            }
            catch(Exception e)
            {
                UnexpectedException(e);
            }
        }
        public void TestWriteTryLockWhenReadLockedFair()
        {
            ReentrantReadWriteLock locker = new ReentrantReadWriteLock(true);
            locker.ReadLock.Lock();
            Thread t = new Thread(TestWriteTryLockWhenReadLockedFairRun);

            try
            {
                t.Start(locker);
                t.Join();
                locker.ReadLock.UnLock();
            }
            catch(Exception e)
            {
                UnexpectedException(e);
            }
        }
 public void TestHasQueuedThreadNRE()
 {
     ReentrantReadWriteLock sync = new ReentrantReadWriteLock();
     try
     {
         sync.HasQueuedThread(null);
         ShouldThrow();
     }
     catch (NullReferenceException)
     {
     }
 }
     public void TestReadHoldingWriteLock3()
     {
         ReentrantReadWriteLock locker = new ReentrantReadWriteLock();
         locker.WriteLock.Lock();
         Thread t1 = new Thread(TestReadHoldingWriteLock3Run);
         Thread t2 = new Thread(TestReadHoldingWriteLock3Run);
 
         try
         {
             t1.Start(locker);
             t2.Start(locker);
             locker.ReadLock.Lock();
             locker.ReadLock.UnLock();
             Thread.Sleep(SHORT_DELAY_MS);
             locker.ReadLock.Lock();
             locker.ReadLock.UnLock();
             locker.WriteLock.UnLock();
             t1.Join(MEDIUM_DELAY_MS);
             t2.Join(MEDIUM_DELAY_MS);
             Assert.IsTrue(!t1.IsAlive);
             Assert.IsTrue(!t2.IsAlive);
 
         }
         catch(Exception e)
         {
             UnexpectedException(e);
         }
     }
 public void TestAwaitUntilTimeout()
 {
     ReentrantReadWriteLock locker = new ReentrantReadWriteLock();
     Condition c = locker.WriteLock.NewCondition();
     try
     {
         locker.WriteLock.Lock();
         c.AwaitUntil(DateTime.Now.AddMilliseconds(250));
         locker.WriteLock.UnLock();
     }
     catch (Exception e)
     {
         UnexpectedException(e);
     }
 }