/// <summary> /// Initializes a new instance of the <see cref="BucketCircularArray{T}"/> class. /// </summary> /// <param name="size">The maximum number of buckets to store.</param> public BucketCircularArray(int size) { AtomicReferenceArray <T> buckets = new AtomicReferenceArray <T>(size + 1); // + 1 as extra room for the add/remove BucketCircularArrayListState listState = new BucketCircularArrayListState(buckets, 0, 0); this.state = new AtomicReference <BucketCircularArrayListState>(listState); }
public void AtomicReferenceArray_Should_Copy_Source(MemoryOrder memoryOrder) { var item1 = new object(); var item2 = new object(); var source = new object[] { item1, null, item2, null }; var ar = new AtomicReferenceArray <object>(source, memoryOrder); Assert.True(source.SequenceEqual(ar)); Assert.Null(source[1]); Assert.Null(ar[1]); source[1] = new object(); Assert.False(source.SequenceEqual(ar)); Assert.Null(source[3]); Assert.Null(ar[3]); Assert.Null(source[3]); Assert.Null(ar[3]); source[3] = new object(); Assert.NotNull(source[3]); Assert.Null(ar[3]); Assert.False(source.SequenceEqual(ar)); }
/** * Executes a task, on N threads, all starting at the same time. * * @param nThreads the number of threads to execute * @param task the task to execute in each thread * @param baseThreadName the base name for each thread in this task set * @return the result of each task and the full execution time, in * nanoseconds */ public static TestResult <T> timeTasks <T>(int nThreads, Func <T> task, String baseThreadName) where T : class { CountdownEvent startGate = new CountdownEvent(1); CountdownEvent endGate = new CountdownEvent(nThreads); AtomicReferenceArray <T> results = new AtomicReferenceArray <T>(nThreads); IList <Thread> threads = new List <Thread>(nThreads); for (int i = 0; i < nThreads; i++) { int index = i; var thread = new Thread(() => { startGate.Wait(); try { results[index] = task(); } finally { endGate.Signal(); } }) { Name = baseThreadName + "-" + i, IsBackground = true }; thread.Start(); threads.Add(thread); } var sw = Stopwatch.StartNew(); startGate.Signal(); endGate.Wait(); return(new TestResult <T>(sw.Elapsed.Ticks, toList(results))); }
private bool AddClientHoldingLock(ForsetiClient client) { while (true) { for (int i = 0; i < _clientsHoldingThisLock.Length; i++) { AtomicReferenceArray <ForsetiClient> holders = _clientsHoldingThisLock[i]; if (holders == null) { holders = AddHolderArray(i); } for (int j = 0; j < holders.length(); j++) { ForsetiClient c = holders.get(j); if (c == null) { // TODO This means we do CAS on each entry, very likely hitting a lot of failures until we // TODO find a slot. We should look into better strategies here. // TODO One such strategy could be binary searching for a free slot, and then linear scan // TODO after that if the CAS fails on the slot we found with binary search. if (holders.compareAndSet(j, null, client)) { return(true); } } } } } }
public RunnableAnonymousInnerClass(LabelScanStoreTxApplyRaceIT outerInstance, AtomicReferenceArray <Node> nodeHeads, int guy) { this.outerInstance = outerInstance; this._nodeHeads = nodeHeads; this._guy = guy; random = ThreadLocalRandom.current(); }
public void AtomicReferenceArray_Store_MemoryOrder_Should_Success(MemoryOrder order) { var source = Enumerable.Range(0, 3).Select(x => new object()).ToArray(); var atomicReferenceArray = new AtomicReferenceArray <object>(source.Length, order); for (int i = 0; i < atomicReferenceArray.Count; i++) { atomicReferenceArray.Store(i, source[i], order); } for (int i = 0; i < atomicReferenceArray.Count; i++) { Assert.Equal(source[i], atomicReferenceArray.Load(i, order)); } for (int i = 0; i < atomicReferenceArray.Count; i++) { atomicReferenceArray.Store(i, source[i], order); } for (int i = 0; i < atomicReferenceArray.Count; i++) { Assert.Equal(source[i], atomicReferenceArray.Load(i, order)); } }
public void AtomicReferenceArray_Store_Should_Success(object initialValue, object storeValue, MemoryOrder order) { var atomicReferenceArray = new AtomicReferenceArray <object>(new object[1], MemoryOrder.Relaxed); atomicReferenceArray.Store(0, storeValue, order); Assert.Equal(storeValue, atomicReferenceArray[0]); }
public BucketCircularArray(int size) { var buckets = new AtomicReferenceArray<Bucket>(size + 1); // + 1 as extra room for the add/remove; _state = new AtomicReference<ListState>(new ListState(this, buckets, 0, 0)); _dataLength = buckets.Length; _numBuckets = size; }
private ThreadStart Inserter <T1>(AtomicReferenceArray <T1> lastBatches, Generator[] generators, System.Threading.CountdownEvent insertersDone, ReadWriteLock updateLock, int slot) where T1 : Org.Neo4j.Kernel.Api.Index.IndexEntryUpdate <T1> { int worstCaseEntriesPerThread = BATCHES_PER_THREAD * MAX_BATCH_SIZE; return(throwing(() => { try { Generator generator = generators[slot] = new Generator(this, MAX_BATCH_SIZE, Random.seed() + slot, slot * worstCaseEntriesPerThread); for (int j = 0; j < BATCHES_PER_THREAD; j++) { IList <IndexEntryUpdate <object> > batch = generator.Batch(); updateLock.readLock().@lock(); try { _populator.add(batch); } finally { updateLock.readLock().unlock(); } lastBatches.set(slot, batch); } } finally { // This helps the updater know when to stop updating insertersDone.Signal(); } })); }
public RunnableAnonymousInnerClassHelper(TestWeakIdentityMap outerInstance, int keyCount, WeakIdentityMap <object, int?> map, AtomicReferenceArray <object> keys, Random rnd) { this.outerInstance = outerInstance; this.keyCount = keyCount; this.map = map; this.keys = keys; this.rnd = rnd; }
public void AtomicReferenceArray_Store_Should_Fail() { var atomicReferenceArray = new AtomicReferenceArray <object>(new object[1]); Assert.Throws <InvalidOperationException>(() => atomicReferenceArray.Store(0, new object(), MemoryOrder.Acquire)); #pragma warning disable 618 Assert.Throws <NotSupportedException>(() => atomicReferenceArray.Store(0, new object(), MemoryOrder.Consume)); #pragma warning restore 618 }
public void AtomicReferenceArray_Load_Should_Fail() { var atomicReferenceArray = new AtomicReferenceArray <object>(new [] { new object() }); Assert.Throws <InvalidOperationException>(() => atomicReferenceArray.Load(0, MemoryOrder.Release)); #pragma warning disable 618 Assert.Throws <NotSupportedException>(() => atomicReferenceArray.Load(0, MemoryOrder.Consume)); #pragma warning restore 618 }
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); } }
/** * Migrates the data from the atomic array to a {@link List} for easier * consumption. * * @param data the per-thread results from the test * @return the per-thread results as a standard collection */ private static IList <T> toList <T>(AtomicReferenceArray <T> data) where T : class { var list = new List <T>(data.Length); for (int i = 0; i < data.Length; i++) { list.Add(data[i]); } return(list); }
public void AtomicReferenceArray_Load_Should_Success() { var obj = new object(); var atomicReferenceArray = new AtomicReferenceArray <object>(new[] { obj }); Assert.Equal(obj, atomicReferenceArray.Load(0, MemoryOrder.Relaxed)); Assert.Equal(obj, atomicReferenceArray.Load(0, MemoryOrder.Acquire)); Assert.Equal(obj, atomicReferenceArray.Load(0, MemoryOrder.AcqRel)); Assert.Equal(obj, atomicReferenceArray.Load(0, MemoryOrder.SeqCst)); }
private AtomicReferenceArray <ForsetiClient> AddHolderArray(int slot) { lock (this) { if (_clientsHoldingThisLock[slot] == null) { _clientsHoldingThisLock[slot] = new AtomicReferenceArray <ForsetiClient>(( int )(8 * Math.Pow(8, slot))); } return(_clientsHoldingThisLock[slot]); } }
public void AtomicReferenceArray_Items_With_Length_Ctor_Should_Be_Null(int length, MemoryOrder memoryOrder) { var ar = new AtomicReferenceArray <object>(length, memoryOrder); foreach (var o in ar) { Assert.Null(o); } for (int i = 0; i < ar.Count; i++) { Assert.Null(ar[i]); } }
public void AtomicReferenceArray_Indexer_MemoryOrder_Should_Success(MemoryOrder order) { var source = Enumerable.Range(0, 3).Select(x => new object()).ToArray(); var atomicReferenceArray = new AtomicReferenceArray <object>(source.Length, order); for (int i = 0; i < atomicReferenceArray.Count; i++) { Assert.Equal(null, atomicReferenceArray[i]); atomicReferenceArray[i] = source[i]; } for (int i = 0; i < atomicReferenceArray.Count; i++) { Assert.Equal(source[i], atomicReferenceArray[i]); } }
public ListState(BucketCircularArray ca, AtomicReferenceArray<Bucket> data, int head, int tail) { _ca = ca; _head = head; _listtail = tail; if (head == 0 && tail == 0) { _size = 0; } else { _size = (tail + ca._dataLength - head) % ca._dataLength; } _data = data; }
//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()); } }
/// <summary> /// Initializes a new instance of the <see cref="BucketCircularArrayListState"/> class. /// </summary> /// <param name="data">The internal array storing the items.</param> /// <param name="head">The index of the head.</param> /// <param name="tail">The index of the tail.</param> public BucketCircularArrayListState(AtomicReferenceArray <T> data, int head, int tail) { this.head = head; this.tail = tail; this.dataLength = data.Length; this.numBuckets = data.Length - 1; if (head == 0 && tail == 0) { this.size = 0; } else { this.size = (tail + this.dataLength - head) % this.dataLength; } this.data = data; }
/// <summary> /// Create a new cache with a fixed size entry table and @Lock table. /// </summary> /// <param name="tSize">number of entries in the entry hash table.</param> /// <param name="lockCount"> /// number of entries in the <see cref="LockTarget"/> table. This is the maximum /// concurrency rate for creation of new objects through /// <see cref="load(PackFile, long)"/> invocations. /// </param> internal OffsetCache(int tSize, int lockCount) { if (tSize < 1) { throw new ArgumentException("tSize must be >= 1"); } if (lockCount < 1) { throw new ArgumentException("lockCount must be >= 1"); } queue = new Queue(); _tableSize = tSize; _clock = new AtomicValue <long>(1); _table = new AtomicReferenceArray <Entry <V> >(_tableSize); _locks = new LockTarget[lockCount]; for (int i = 0; i < _locks.Length; i++) { _locks[i] = new LockTarget(); } _evictLock = new AutoResetEvent(true); var eb = (int)(_tableSize * .1); if (64 < eb) { eb = 64; } else if (eb < 4) { eb = 4; } if (_tableSize < eb) { eb = _tableSize; } _evictBatch = eb; }
/// <summary> /// The test case is basically loads of concurrent CREATE/DELETE NODE or sometimes just CREATE, keeping the created node in an array /// for dedicated deleter threads to pick up and delete as fast as they can see them. This concurrently with large creation transactions. /// </summary> //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldStressIt() throws Throwable //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldStressIt() { // given Race race = (new Race()).withMaxDuration(5, TimeUnit.SECONDS); AtomicReferenceArray <Node> nodeHeads = new AtomicReferenceArray <Node>(_numberOfCreators); for (int i = 0; i < _numberOfCreators; i++) { race.AddContestant(Creator(nodeHeads, i)); } race.AddContestants(NUMBER_OF_DELETORS, Deleter(nodeHeads)); // when race.Go(); // then DatabaseLayout dbLayout = Db.databaseLayout(); Db.shutdownAndKeepStore(); assertTrue((new ConsistencyCheckService()).runFullConsistencyCheck(dbLayout, defaults(), NONE, toOutputStream(System.out), false, new ConsistencyFlags(true, true, true, true, false)).Successful); }
public virtual void TestConcurrentHashMap() { // don't make threadCount and keyCount random, otherwise easily OOMs or fails otherwise: const int threadCount = 8, keyCount = 1024; RunnableAnonymousInnerClassHelper[] workers = new RunnableAnonymousInnerClassHelper[threadCount]; WeakIdentityMap<object, int?> map = WeakIdentityMap<object, int?>.NewConcurrentHashMap(Random().NextBoolean()); // we keep strong references to the keys, // so WeakIdentityMap will not forget about them: AtomicReferenceArray<object> keys = new AtomicReferenceArray<object>(keyCount); for (int j = 0; j < keyCount; j++) { keys[j] = new object(); } try { for (int t = 0; t < threadCount; t++) { Random rnd = new Random(Random().Next()); var worker = new RunnableAnonymousInnerClassHelper(this, keyCount, map, keys, rnd); workers[t] = worker; worker.Start(); } } finally { foreach (var w in workers) { w.Join(1000L); } } // LUCENENET: Since assertions were done on the other threads, we need to check the // results here. for (int i = 0; i < workers.Length; i++) { assertTrue(string.Format(CultureInfo.InvariantCulture, "worker thread {0} of {1} failed \n" + workers[i].Error, i, workers.Length), workers[i].Error == null); } // clear strong refs for (int j = 0; j < keyCount; j++) { keys[j] = null; } // check that GC does not cause problems in reap() method: int size = map.Size(); for (int i = 0; size > 0 && i < 10; i++) { try { GC.Collect(); int newSize = map.Size(); Assert.IsTrue(size >= newSize, "previousSize(" + size + ")>=newSize(" + newSize + ")"); size = newSize; Thread.Sleep(new TimeSpan(100L)); int c = 0; for (IEnumerator<object> it = map.Keys.GetEnumerator(); it.MoveNext();) { Assert.IsNotNull(it.Current); c++; } newSize = map.Size(); Assert.IsTrue(size >= c, "previousSize(" + size + ")>=iteratorSize(" + c + ")"); Assert.IsTrue(c >= newSize, "iteratorSize(" + c + ")>=newSize(" + newSize + ")"); size = newSize; } catch (ThreadInterruptedException ie) { } } }
private ThreadStart Updater <T1, T2>(AtomicReferenceArray <T1> lastBatches, System.Threading.CountdownEvent insertersDone, ReadWriteLock updateLock, ICollection <T2> updates) where T1 : Org.Neo4j.Kernel.Api.Index.IndexEntryUpdate <T1> { return(throwing(() => { // Entity ids that have been removed, so that additions can reuse them IList <long> removed = new List <long>(); RandomValues randomValues = RandomValues.create(new Random(Random.seed() + THREADS)); while (insertersDone.CurrentCount > 0) { // Do updates now and then Thread.Sleep(10); updateLock.writeLock().@lock(); try { using (IndexUpdater updater = _populator.newPopulatingUpdater(_nodePropertyAccessor)) { for (int i = 0; i < THREADS; i++) { IList <IndexEntryUpdate <object> > batch = lastBatches.get(i); if (batch != null) { IndexEntryUpdate <object> update = null; switch (randomValues.Next(3)) { case 0: // add if (!removed.Empty) { long?id = removed.remove(randomValues.Next(removed.size())); update = add(id, Descriptor, ValueGenerator.apply(randomValues)); } break; case 1: // remove IndexEntryUpdate <object> removal = batch.get(randomValues.Next(batch.size())); update = remove(removal.EntityId, Descriptor, removal.values()); removed.add(removal.EntityId); break; case 2: // change removal = batch.get(randomValues.Next(batch.size())); change(removal.EntityId, Descriptor, removal.values(), toArray(ValueGenerator.apply(randomValues))); break; default: throw new System.ArgumentException(); } if (update != null) { updater.process(update); updates.Add(update); } } } } } finally { updateLock.writeLock().unlock(); } } })); }
private ThreadStart Deleter(AtomicReferenceArray <Node> nodeHeads) { return(new RunnableAnonymousInnerClass2(this, nodeHeads)); }
public virtual void TestConcurrentHashMap() { // don't make threadCount and keyCount random, otherwise easily OOMs or fails otherwise: const int threadCount = 8, keyCount = 1024; RunnableAnonymousInnerClassHelper[] workers = new RunnableAnonymousInnerClassHelper[threadCount]; WeakIdentityMap <object, int?> map = WeakIdentityMap <object, int?> .NewConcurrentHashMap(Random().NextBoolean()); // we keep strong references to the keys, // so WeakIdentityMap will not forget about them: AtomicReferenceArray <object> keys = new AtomicReferenceArray <object>(keyCount); for (int j = 0; j < keyCount; j++) { keys[j] = new object(); } try { for (int t = 0; t < threadCount; t++) { Random rnd = new Random(Random().Next()); var worker = new RunnableAnonymousInnerClassHelper(this, keyCount, map, keys, rnd); workers[t] = worker; worker.Start(); } } finally { foreach (var w in workers) { w.Join(); } } // LUCENENET: Since assertions were done on the other threads, we need to check the // results here. for (int i = 0; i < workers.Length; i++) { assertTrue(string.Format(CultureInfo.InvariantCulture, "worker thread {0} of {1} failed \n" + workers[i].Error, i, workers.Length), workers[i].Error == null); } // clear strong refs for (int j = 0; j < keyCount; j++) { keys[j] = null; } // check that GC does not cause problems in reap() method: int size = map.Count; for (int i = 0; size > 0 && i < 10; i++) { #if !NETSTANDARD1_6 try { #endif GC.Collect(); int newSize = map.Count; Assert.IsTrue(size >= newSize, "previousSize(" + size + ")>=newSize(" + newSize + ")"); size = newSize; Thread.Sleep(new TimeSpan(100L)); int c = 0; foreach (object k in map.Keys) { Assert.IsNotNull(k); c++; } newSize = map.Count; Assert.IsTrue(size >= c, "previousSize(" + size + ")>=iteratorSize(" + c + ")"); Assert.IsTrue(c >= newSize, "iteratorSize(" + c + ")>=newSize(" + newSize + ")"); size = newSize; #if !NETSTANDARD1_6 } #pragma warning disable 168 catch (ThreadInterruptedException ie) #pragma warning restore 168 { } #endif } }
internal Table(int bits) { this.ids = new AtomicReferenceArray<ObjectId>(1 << bits); this.shift = 32 - bits; this.bits = bits; }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @ImmutableConstructor private DefaultIborCapFloorScenarioMarketData(IborCapFloorMarketDataLookup lookup, com.opengamma.strata.data.scenario.ScenarioMarketData marketData) private DefaultIborCapFloorScenarioMarketData(IborCapFloorMarketDataLookup lookup, ScenarioMarketData marketData) { this.lookup = ArgChecker.notNull(lookup, "lookup"); this.marketData = ArgChecker.notNull(marketData, "marketData"); this.cache = new AtomicReferenceArray <IborCapFloorMarketData>(marketData.ScenarioCount); }
public virtual void TestConcurrentHashMap() { // don't make threadCount and keyCount random, otherwise easily OOMs or fails otherwise: const int threadCount = 8, keyCount = 1024; ExecutorService exec = Executors.newFixedThreadPool(threadCount, new NamedThreadFactory("testConcurrentHashMap")); WeakIdentityMap <object, int?> map = WeakIdentityMap <object, int?> .NewConcurrentHashMap(Random().NextBoolean()); // we keep strong references to the keys, // so WeakIdentityMap will not forget about them: AtomicReferenceArray <object> keys = new AtomicReferenceArray <object>(keyCount); for (int j = 0; j < keyCount; j++) { keys.Set(j, new object()); } try { for (int t = 0; t < threadCount; t++) { Random rnd = new Random(Random().Next()); exec.execute(new RunnableAnonymousInnerClassHelper(this, keyCount, map, keys, rnd)); } } finally { exec.shutdown(); while (!exec.awaitTermination(1000L, TimeUnit.MILLISECONDS)) { ; } } // clear strong refs for (int j = 0; j < keyCount; j++) { keys.Set(j, null); } // check that GC does not cause problems in reap() method: int size = map.Size(); for (int i = 0; size > 0 && i < 10; i++) { try { System.runFinalization(); System.gc(); int newSize = map.Size(); Assert.IsTrue(size >= newSize, "previousSize(" + size + ")>=newSize(" + newSize + ")"); size = newSize; Thread.Sleep(new TimeSpan(100L)); int c = 0; for (IEnumerator <object> it = map.Keys.GetEnumerator(); it.MoveNext();) { Assert.IsNotNull(it.Current); c++; } newSize = map.Size(); Assert.IsTrue(size >= c, "previousSize(" + size + ")>=iteratorSize(" + c + ")"); Assert.IsTrue(c >= newSize, "iteratorSize(" + c + ")>=newSize(" + newSize + ")"); size = newSize; } catch (ThreadInterruptedException ie) { } } }
public void AtomicReferenceArray_Should_Copy_Source(MemoryOrder memoryOrder) { var item1 = new object(); var item2 = new object(); var source = new object[] { item1, null, item2, null}; var ar = new AtomicReferenceArray<object>(source, memoryOrder); Assert.True(source.SequenceEqual(ar)); Assert.Null(source[1]); Assert.Null(ar[1]); source[1] = new object(); Assert.False(source.SequenceEqual(ar)); Assert.Null(source[3]); Assert.Null(ar[3]); Assert.Null(source[3]); Assert.Null(ar[3]); source[3] = new object(); Assert.NotNull(source[3]); Assert.Null(ar[3]); Assert.False(source.SequenceEqual(ar)); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @ImmutableConstructor private DefaultFxOptionScenarioMarketData(FxOptionMarketDataLookup lookup, com.opengamma.strata.data.scenario.ScenarioMarketData marketData) private DefaultFxOptionScenarioMarketData(FxOptionMarketDataLookup lookup, ScenarioMarketData marketData) { this.lookup = ArgChecker.notNull(lookup, "lookup"); this.marketData = ArgChecker.notNull(marketData, "marketData"); this.cache = new AtomicReferenceArray <FxOptionMarketData>(marketData.ScenarioCount); }
internal Table(int bits) { this.ids = new AtomicReferenceArray <ObjectId>(1 << bits); this.shift = 32 - bits; this.bits = bits; }
public virtual void TestConcurrentHashMap() { // don't make threadCount and keyCount random, otherwise easily OOMs or fails otherwise: const int threadCount = 8, keyCount = 1024; ExecutorService exec = Executors.newFixedThreadPool(threadCount, new NamedThreadFactory("testConcurrentHashMap")); WeakIdentityMap<object, int?> map = WeakIdentityMap<object, int?>.NewConcurrentHashMap(Random().NextBoolean()); // we keep strong references to the keys, // so WeakIdentityMap will not forget about them: AtomicReferenceArray<object> keys = new AtomicReferenceArray<object>(keyCount); for (int j = 0; j < keyCount; j++) { keys.Set(j, new object()); } try { for (int t = 0; t < threadCount; t++) { Random rnd = new Random(Random().Next()); exec.execute(new RunnableAnonymousInnerClassHelper(this, keyCount, map, keys, rnd)); } } finally { exec.shutdown(); while (!exec.awaitTermination(1000L, TimeUnit.MILLISECONDS)) ; } // clear strong refs for (int j = 0; j < keyCount; j++) { keys.Set(j, null); } // check that GC does not cause problems in reap() method: int size = map.Size(); for (int i = 0; size > 0 && i < 10; i++) { try { System.runFinalization(); System.gc(); int newSize = map.Size(); Assert.IsTrue(size >= newSize, "previousSize(" + size + ")>=newSize(" + newSize + ")"); size = newSize; Thread.Sleep(new TimeSpan(100L)); int c = 0; for (IEnumerator<object> it = map.Keys.GetEnumerator(); it.MoveNext(); ) { Assert.IsNotNull(it.Current); c++; } newSize = map.Size(); Assert.IsTrue(size >= c, "previousSize(" + size + ")>=iteratorSize(" + c + ")"); Assert.IsTrue(c >= newSize, "iteratorSize(" + c + ")>=newSize(" + newSize + ")"); size = newSize; } catch (ThreadInterruptedException ie) { } } }
public RunnableAnonymousInnerClassHelper(TestWeakIdentityMap outerInstance, int keyCount, WeakIdentityMap<object, int?> map, AtomicReferenceArray<object> keys, Random rnd) { this.OuterInstance = outerInstance; this.KeyCount = keyCount; this.Map = map; this.Keys = keys; this.Rnd = rnd; }
public void AtomicReferenceArray_Items_With_Length_Ctor_Should_Be_Null(int length, MemoryOrder memoryOrder) { var ar = new AtomicReferenceArray<object>(length, memoryOrder); foreach (var o in ar) { Assert.Null(o); } for (int i = 0; i < ar.Count; i++) { Assert.Null(ar[i]); } }