public static Vec2D GetFromPool(float x = 0f, float y = 0f) { Vec2D vec = Pool.Acquire(); vec.SetTo(x, y); return(vec); }
public void TestPoolChangeMaxCapacity() { var pool = new Pool <object>(3, pool => pool.NewPoolEntry(new object())); var obj1 = pool.Acquire(1); Assert.IsNotNull(obj1); var obj2 = pool.Acquire(1); Assert.IsNotNull(obj2); Assert.AreNotEqual(obj1, obj2); pool.MaxCapacity = 4; var obj3 = pool.Acquire(1); Assert.IsNotNull(obj3); var obj4 = pool.Acquire(1); Assert.IsNotNull(obj4); Assert.ThrowsException <TimeoutException>(() => pool.Acquire(1)); pool.MaxCapacity = 3; pool.Release(obj4); pool.Release(obj3); pool.Release(obj2); pool.Release(obj1); obj1 = pool.Acquire(1); pool.Acquire(1); pool.Acquire(1); Assert.ThrowsException <TimeoutException>(() => pool.Acquire(1)); pool.Release(obj1); pool.Acquire(1); }
public void GIVEN_failed_consumer_THEN_it_is_not_returned_to_the_pool() { var pool = new Pool<XmsPooledConsumer>(1, p => CreateFailingStub(p), store); Assert.That(store.Count, Is.EqualTo(0)); XmsPooledConsumer notExpected; XmsPooledConsumer actual; using (var consumer = pool.Acquire()) { Assert.That(store.Count, Is.EqualTo(0)); notExpected = consumer; Assert.Throws<TestException>(() => consumer.ReceiveNoWait()); } Assert.That(store.Count, Is.EqualTo(0)); using (var consumer = pool.Acquire()) { actual = consumer; } Assert.That(store.Count, Is.EqualTo(1)); Assert.That(actual, Is.Not.SameAs(notExpected)); }
public void Test_ReleaseTwiceWithAcquire() { var obj = new object(); var pool = new Pool<object>(() => obj, AccessStrategy.LIFO, LoadingStrategy.Eager, 1) .AttachDebugger(new ReleaseDebugger<object>(state => { throw new InvalidOperationException(); })); pool.Release(pool.Acquire()); pool.Release(pool.Acquire()); }
public void TestPoolBasic() { var pool = new Pool <object>(2, pool => pool.NewPoolEntry(new object())); var obj1 = pool.Acquire(); Assert.IsNotNull(obj1); var obj2 = pool.Acquire(); Assert.IsNotNull(obj2); }
public void TestTryRemoveReleasedItemFromPool() { using (var pool = new Pool <Item>(x => new Item(), NoOpMetrics.Instance, new SilentLog())) { var item1 = pool.Acquire(); var item2 = pool.Acquire(); pool.Release(item1); pool.Release(item2); Assert.Throws <RemoveFromPoolFailedException>(() => pool.Remove(item2)); } }
public void TestPoolRetrieveTimeout() { var pool = new Pool <object>(2, pool => pool.NewPoolEntry(new object())); var obj1 = pool.Acquire(); Assert.IsNotNull(obj1); var obj2 = pool.Acquire(); Assert.IsNotNull(obj2); Assert.ThrowsException <TimeoutException>(() => pool.Acquire(1000)); }
public void DisposeAndReleaseDeadItemsThroughAcquire() { using (var pool = new Pool <Item>(x => new Item(), NoOpMetrics.Instance, new SilentLog())) { var item1 = pool.Acquire(); item1.IsAlive = false; pool.Release(item1); var item2 = pool.Acquire(); Assert.That(item2, Is.Not.EqualTo(item1)); Assert.That(item1.Disposed); } }
public void Test_ReleaseEqualObjects() { var pool = new Pool<string>(() => new string(new[] { 'a', 'b', 'c' }), AccessStrategy.LIFO, LoadingStrategy.Eager, 2) .AttachDebugger(new ReleaseDebugger<string>(state => { throw new InvalidOperationException(); })); string s1 = pool.Acquire(); string s2 = pool.Acquire(); Assert.AreEqual(s1, s2); Assert.AreEqual(s1.GetHashCode(), s2.GetHashCode()); pool.Release(s1); pool.Release(s2); Assert.AreEqual(2, pool.Allocated); Assert.AreEqual(2, pool.Available); }
public void YouCanGetTheCountOfAcquiredElements() { Pool <Test> pool = new Pool <Test>(10); var test1 = pool.Acquire(); Assert.AreEqual(pool.Count, 1); var test2 = pool.Acquire(); Assert.AreEqual(pool.Count, 2); pool.Release(ref test1); Assert.AreEqual(pool.Count, 1); pool.Release(ref test2); Assert.AreEqual(pool.Count, 0); }
public void TestPoolSimpleReleaseSemantics() { var pool = new Pool <object>(2, pool => pool.NewPoolEntry(new object())); var obj1 = pool.Acquire(); Assert.IsNotNull(obj1); var obj2 = pool.Acquire(); Assert.IsNotNull(obj2); pool.Release(obj1); obj2 = pool.Acquire(1000); Assert.IsNotNull(obj2); Assert.AreEqual(obj1, obj2); }
public void TestRemoveItemFromPool() { using (var pool = new Pool <Item>(x => new Item(), NoOpMetrics.Instance, new SilentLog())) { var item1 = pool.Acquire(); var item2 = pool.Acquire(); pool.Release(item1); pool.Remove(item2); var item3 = pool.Acquire(); var item4 = pool.Acquire(); Assert.That(item3, Is.EqualTo(item1)); Assert.That(item4, Is.Not.EqualTo(item1) & Is.Not.EqualTo(item2)); } }
/// <summary> /// Creates particles with associated initializers. /// </summary> /// <param name="count">The number to create.</param> /// <param name="currentTime">The current simulation time.</param> /// <param name="toList">The list the particles will be added to to prevent object allocation</param> /// <returns>The newly created particles.</returns> public List <Particle> CreatParticles(int count, float currentTime, List <Particle> toList) { List <Particle> particles = toList; if (particles == null) { particles = new List <Particle>(); } if (count > 0) { for (int i = 0; i < count; i++) { var particle = Pool.Acquire(); particle.Init(); particles.Add(particle); } var initializers = _initializerCollection.Elems; int len = initializers.Count; for (int i = 0; i < len; ++i) { Initializer init = initializers[i]; init.DoInitialize(particles, currentTime); } } return(particles); }
public static AnimationStripDescriptor Acquire(Texture2D texture, int numFrameRows, int numFrameColumns) { var instance = Pool.Acquire(); instance.Reset(texture, numFrameRows, numFrameColumns); return(instance); }
public void Test_ReleaseGarbage() { var pool = new Pool<object>(() => new object(), AccessStrategy.LIFO, LoadingStrategy.Eager, 1) .AttachDebugger(new ReleaseDebugger<object>(state => { throw new InvalidOperationException(); })); pool.Acquire(); Assert.Throws<InvalidOperationException>(() => pool.Release(new object())); }
public void PlaySound(string name) { Sound s = Array.Find(sounds, sound => sound.name == name); // opgevraagde geluid bestaat if (s != null) { var aud = sources.Acquire(); // aantal spelende geluiden is lager dan de bovengrens if (aud != null) { // kopieer instellingen en speel het geluid af aud.clip = s.clip; aud.volume = s.volume; aud.pitch = s.pitch; aud.loop = s.loop; aud.Play(); } } // opgevraagde geluid bestaat niet else { Debug.LogError("ERROR: Sound " + name + " not found"); } }
public static CachedTextureDescriptor Acquire(Texture2D cachedTexture) { var instance = Pool.Acquire(); instance.Reset(cachedTexture); return(instance); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test void shouldReturnToDelegatePoolIfLocalPoolIsFull() internal virtual void ShouldReturnToDelegatePoolIfLocalPoolIsFull() { // Given Pool <object> delegatePool = mock(typeof(Pool)); when(delegatePool.Acquire()).thenReturn(1337); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final MarshlandPool<Object> pool = new MarshlandPool<>(delegatePool); MarshlandPool <object> pool = new MarshlandPool <object>(delegatePool); object first = pool.Acquire(); object second = pool.Acquire(); object third = pool.Acquire(); // When pool.Release(first); pool.Release(second); pool.Release(third); // Then verify(delegatePool, times(3)).acquire(); verify(delegatePool, times(2)).release(any()); verifyNoMoreInteractions(delegatePool); }
public void DisposeItemsAfterPoolDisposed() { Item item1; Item item2; using (var pool = new Pool <Item>(x => new Item(), NoOpMetrics.Instance, new SilentLog())) { item1 = pool.Acquire(); item2 = pool.Acquire(); pool.Release(item1); pool.Release(item2); item1 = pool.Acquire(); } Assert.That(item1.Disposed); Assert.That(item2.Disposed); }
public void YouCanAcquireAnElementFromThePool() { Pool <Test> pool = new Pool <Test>(1); var test = pool.Acquire(); Assert.IsNotNull(test); }
public void YouCanUseRangeForeachWithThePool() { Random random = new Random(); int capacity = random.Next(3, 100); Pool <Test> pool = new Pool <Test>(101); pool.OnAcquired += (ref Test element) => { element.data = $"{random.Next(10000)}"; }; HashSet <string> data = new HashSet <string>(); for (int i = 0; i < capacity; i++) { var element = pool.Acquire(); data.Add(element.data); } int check = 0; foreach (var acquired in pool) { Assert.IsTrue(data.Contains(acquired.data)); check++; } Assert.AreEqual(check, capacity); }
public void Test_Dispose_4() { Disposable disposable; PoolResourceHolder<Disposable> poolResourceHolder; var pool = new Pool<Disposable>(() => new Disposable(), AccessStrategy.LIFO, LoadingStrategy.Eager, 1); pool.Dispose(); Assert.Throws<ObjectDisposedException>(() => pool.Acquire()); Assert.Throws<ObjectDisposedException>(() => pool.AcquireHolder()); Assert.Throws<ObjectDisposedException>(() => pool.TryAcquire(TimeSpan.FromDays(1), out disposable)); Assert.Throws<ObjectDisposedException>(() => pool.TryAcquireHolder(TimeSpan.FromDays(1), out poolResourceHolder)); Assert.Throws<ObjectDisposedException>(() => pool.TryAcquireImmediately(out disposable)); Assert.Throws<ObjectDisposedException>(() => pool.TryAcquireHolderImmediately(out poolResourceHolder)); // Асинхронные методы. try { pool.AcquireAsync().Wait(); Assert.Fail("Must throw exception."); } catch (AggregateException error) { Assert.True(error.InnerExceptions.Single() is ObjectDisposedException); } try { pool.AcquireHolderAsync().Wait(); Assert.Fail("Must throw exception."); } catch (AggregateException error) { Assert.True(error.InnerExceptions.Single() is ObjectDisposedException); } }
static void Main() { try { var obj = new BizObject(); var pool = new Pool <BizObject>(int.MaxValue, p => new PoolEntry <BizObject>(obj)); var stopwatch = new Stopwatch(); var slot = Thread.AllocateDataSlot(); Thread.SetData(slot, new object[] { obj }); BizObject v = obj; stopwatch.Start(); for (var i = 0; i < 1000000; i++) { var entry = pool.Acquire(); v = entry.Value; pool.Release(entry); //var arr = (object[]) Thread.GetData(slot); //var arr = new object[] {obj}; //v = (BizObject)arr[0]; } stopwatch.Stop(); Console.WriteLine(stopwatch.ElapsedMilliseconds); Console.WriteLine(v.IntValue); Console.ReadLine(); } catch (Exception e) { Console.WriteLine(e.Message); } }
public void MultiThreadTest() { using (var pool = new Pool <Item>(x => new Item(), new SilentLog())) { var threads = Enumerable .Range(0, 100) .Select(n => (Action)(() => { // ReSharper disable AccessToDisposedClosure var random = new Random(n * DateTime.UtcNow.Millisecond); for (var i = 0; i < 100; i++) { var item = pool.Acquire(); try { Assert.That(!item.IsUse); Assert.That(!item.Disposed); var item2 = pool.Acquire(); try { Assert.That(!item2.IsUse); Assert.That(!item2.Disposed); item2.Use(TimeSpan.FromMilliseconds(random.Next(100))); } finally { pool.Release(item2); } item.Use(TimeSpan.FromMilliseconds(random.Next(100))); Assert.That(!item.IsUse); Assert.That(!item.Disposed); } finally { pool.Release(item); } Thread.Sleep(TimeSpan.FromMilliseconds(random.Next(100))); } // ReSharper restore AccessToDisposedClosure })) .Select(x => new Thread(() => x())) .ToList(); threads.ForEach(x => x.Start()); threads.ForEach(x => x.Join()); Console.WriteLine(pool.TotalCount); } }
public void Test_Lazy_MinimalAllocations() { var pool = new Pool<object>(() => new object(), AccessStrategy.LIFO, LoadingStrategy.Lazy, 3); for (int i = 0; i < 100; i++) pool.Release(pool.Acquire()); Assert.AreEqual(1, pool.Allocated); Assert.AreEqual(1, pool.Available); }
public void YouCanReleaseAnAcquiredElement() { Pool <Test> pool = new Pool <Test>(1); var test = pool.Acquire(); Assert.IsNotNull(test); pool.Release(ref test); Assert.IsNull(test); }
public void TestTryRemoveItemDoesNotBelongInPool() { using (var pool = new Pool <Item>(x => new Item(), new SilentLog())) { var item1 = pool.Acquire(); pool.Release(item1); Assert.Throws <RemoveFromPoolFailedException>(() => pool.Remove(new Item())); } }
public void TestPoolWithRefCount() { var pool = new Pool <object>(10, pool => pool.NewPoolEntry(new object(), 2)); var obj1 = pool.Acquire(); Assert.IsNotNull(obj1); var obj2 = pool.Acquire(); Assert.IsNotNull(obj2); pool.Release(obj2); var obj3 = pool.Acquire(); Assert.AreNotEqual(obj3, obj2); pool.Release(obj2); var obj4 = pool.Acquire(); Assert.AreEqual(obj4, obj2); }
public static Sound1D Create(string name, Cue cue, Action <string> onFinished) { Sound1D freshSound = Pool.Acquire <Sound1D>(); freshSound.Name = name; freshSound._cue = cue; freshSound.OnFinished = onFinished; return(freshSound); }
public void AcquireAndReleaseItemFromEmptyPool() { var factoryInvokeCount = 0; using (var pool = new Pool <Item>(x => { factoryInvokeCount++; return(new Item()); }, NoOpMetrics.Instance, new SilentLog())) { var item1 = pool.Acquire(); pool.Release(item1); var item2 = pool.Acquire(); Assert.That(item2, Is.EqualTo(item1)); Assert.That(factoryInvokeCount, Is.EqualTo(1)); } }
public void TryReleaseItemTwice() { using (var pool = new Pool <Item>(x => new Item(), NoOpMetrics.Instance, new SilentLog())) { var item1 = pool.Acquire(); pool.Release(item1); Assert.Throws <FailedReleaseItemException>(() => pool.Release(item1)); } }
public void TestPoolReleaseInSeparateThread() { var pool = new Pool <object>(2, pool => pool.NewPoolEntry(new object())); var obj1 = pool.Acquire(); Assert.IsNotNull(obj1); var obj2 = pool.Acquire(); var obj3 = obj2; Assert.IsNotNull(obj2); ThreadPool.QueueUserWorkItem(state => pool.Release(obj1)); obj2 = pool.Acquire(1000); Assert.IsNotNull(obj2); Assert.AreEqual(obj1, obj2); pool.Release(obj3); obj2 = pool.Acquire(); Assert.IsNotNull(obj2); Assert.AreEqual(obj3, obj2); }
/// <summary> /// Clones this sub-tree /// </summary> /// <returns>The clone</returns> public SubTree Clone() { SubTree result = pool != null?pool.Acquire() : new SubTree(null, nodes.Length); int size = GetSize(); Array.Copy(nodes, result.nodes, size); Array.Copy(actions, result.actions, size); return(result); }
public void ShouldReturnInstanceIntoThePoolAndNextCallerShouldGetIt() { var pool = new Pool<XmsPooledProducer>(1, p => CreateFailingStub(p), store); Assert.That(store.Count, Is.EqualTo(0)); IXmsProducer expected; IXmsProducer actual; using (var producer = pool.Acquire()) { expected = producer; } using (var producer = pool.Acquire()) { actual = producer; } Assert.That(store.Count, Is.EqualTo(1)); Assert.That(actual, Is.SameAs(expected)); }
public static CollisionBody Create(TransformableEntity entity, CollisionShape shape) { CollisionBody collider = Pool.Acquire <CollisionBody>(); collider.Owner = entity; collider.Shape = shape; collider.OnCollision += collider.HandleOnCollision; collider.BeforeCollision += collider.HandleBeforeCollision; return(collider); }
public static BroadphaseProxy Create(object client, CollisionGroups group, CollisionGroups mask) { BroadphaseProxy proxy = Pool.Acquire <BroadphaseProxy>(); proxy.ClientObject = client; proxy.CollisionFilterGroup = group; proxy.CollisionFilterMask = mask; CollisionGlobals.TotalProxies++; return(proxy); }
public void Test_Eager() { var pool = new Pool<object>(() => new object(), AccessStrategy.LIFO, LoadingStrategy.Eager, 3); Assert.AreEqual(3, pool.Allocated); Assert.AreEqual(3, pool.Available); pool.Acquire(); Assert.AreEqual(3, pool.Allocated); Assert.AreEqual(2, pool.Available); }
/// <summary> /// Push a token onto the stack /// </summary> /// <param name="index">The token's index in the parsed text</param> public void StackPushToken(int index) { SubTree single = poolSingle.Acquire(); single.SetupRoot(new TableElemRef(TableType.Token, index), TreeAction.None); if (stackNext == stack.Length) { Array.Resize(ref stack, stack.Length + LRkParser.INIT_STACK_SIZE); } stack[stackNext++] = single; }
public void Test_LazyExpanding() { var pool = new Pool<object>(() => new object(), AccessStrategy.LIFO, LoadingStrategy.LazyExpanding, 3); Assert.AreEqual(0, pool.Allocated); Assert.AreEqual(0, pool.Available); object o1 = pool.Acquire(); object o2 = pool.Acquire(); Assert.AreEqual(2, pool.Allocated); Assert.AreEqual(0, pool.Available); pool.Release(o1); pool.Release(o2); Assert.AreEqual(2, pool.Allocated); Assert.AreEqual(2, pool.Available); pool.Acquire(); pool.Acquire(); Assert.AreEqual(3, pool.Allocated); Assert.AreEqual(1, pool.Available); }
public void ShouldNotReturnFaultyInstanceIntoThePoolAndWeCanGetNewOne() { var pool = new Pool<XmsPooledProducer>(1, p => CreateFailingStub(p), store); Assert.That(store.Count, Is.EqualTo(0)); IXmsProducer notExpected; IXmsProducer actual; using (var producer = pool.Acquire()) { notExpected = producer; Assert.Throws<TestException>(() => producer.Send(null)); } using (var producer = pool.Acquire()) { actual = producer; } Assert.That(store.Count, Is.EqualTo(1)); Assert.That(actual, Is.Not.SameAs(notExpected)); }
public void GIVEN_non_transactional_pool_WHEN_send_THEN_message_is_enqueued() { using (var producer = new XmsProducer(address, false)) producer.SendTestMessage(address); IBM.XMS.IMessage message; using (var pool = new Pool<XmsPooledConsumer>(2, p => new XmsPooledConsumer(p, new XmsConsumer(address, false)), store)) using (var producer = pool.Acquire()) { message = producer.ReceiveNoWait(); } Assert.That(message,Is.Not.Null); }
public void Test_Speed() { var pool = new Pool<object>(() => new object(), AccessStrategy.LIFO, LoadingStrategy.Eager, 1); long cycles = 0; TimeSpan testTime = TimeSpan.FromSeconds(1); var sw = Stopwatch.StartNew(); while (sw.Elapsed < testTime) { pool.Release(pool.Acquire()); cycles++; } Console.Out.WriteLine("Done {0} Acquire-Release cycles in 1 second.", cycles); }
public void GIVEN_existing_producer_in_pool_WHEN_aquiring_producer_THEN_the_existing_producer_is_returned() { var pool = new Pool<XmsPooledProducer>(1, p => CreateFailingStub(p), store); Assert.That(store.Count, Is.EqualTo(0)); XmsPooledProducer expected; XmsPooledProducer actual; using (var producer = pool.Acquire()) { Assert.That(store.Count, Is.EqualTo(0)); expected = producer; } Assert.That(store.Count, Is.EqualTo(1)); using (var producer = pool.Acquire()) { actual = producer; } Assert.That(store.Count, Is.EqualTo(1)); Assert.That(actual, Is.SameAs(expected)); }
static void Main(string[] args) { using (Pool<IFoo> pool = new Pool<IFoo>(PoolSize, p => new PooledFoo(p), LoadingMode.Eager, AccessMode.Fifo)) { using (ManualResetEvent finishedEvent = new ManualResetEvent(false)) { int remaining = 10; for (int i = 0; i < 10; i++) { int q = i; ThreadPool.QueueUserWorkItem(s => { Console.WriteLine("Thread started: {0}", q); for (int j = 0; j < 50; j++) { using (IFoo foo = pool.Acquire()) using (IFoo foo2 = pool.Acquire()) { foo.Test(); foo2.Test(); } } if (Interlocked.Decrement(ref remaining) == 0) { finishedEvent.Set(); } }); } finishedEvent.WaitOne(); } Console.WriteLine("Threaded partial load test finished."); Console.WriteLine(); } Console.ReadLine(); }
public void GIVEN_non_transactional_pool_WHEN_send_THEN_message_is_enqueued() { using (var pool = new Pool<XmsPooledProducer>(2, p => new XmsPooledProducer(p, new XmsProducer(address, false)), store)) using (var producer = pool.Acquire()) { producer.SendTestMessage(address); } address.AssertMessageCount(1); }
public void TestRelease() { _pool = new Pool<Connection>(10, _factory, LoadingMode.Lazy, AccessMode.FIFO); var connection = _pool.Acquire(); Assert.IsNotNull(connection); _pool.Release(connection); }
public void Test_That_Twenty_Items_Are_Acquired() { var count = 0; _pool = new Pool<Connection>(10, _factory, LoadingMode.LazyExpanding, AccessMode.FIFO); for (int i = 0; i < 20; i++) { var connection = _pool.Acquire(); if (connection != null) { count++; } //_pool.Release(connection); } Assert.AreEqual(20, count); }