Пример #1
0
        public void TestChangeListenerNotification()
        {
            const int numDocs       = 50;
            var       atomicInteger = new AtomicInteger(0);

            database.Changed += (sender, e) => atomicInteger.IncrementAndGet();
            CreateDocuments(database, numDocs);
            Assert.AreEqual(numDocs, atomicInteger.Get());
        }
Пример #2
0
        /// <summary>
        /// 服务并发量自增
        /// </summary>

        internal void IncrementConcurrentExecutionCount()
        {
            var serviceCount = serviceConcurrentExecutionCount.IncrementAndGet();

            if (serviceCount > serviceMaxConcurrentExecutionCount.Value)
            {
                serviceMaxConcurrentExecutionCount.GetAndSet(serviceCount);
            }
        }
Пример #3
0
            public TestResults(int happenings)
            {
                var times = new AtomicInteger(0);

                safely = AccessSafely
                         .AfterCompleting(happenings)
                         .WritingWith <int>("times", _ => times.IncrementAndGet())
                         .ReadingWith("times", times.Get);
            }
    public ICompletes <Response> DefineWith(Data data)
    {
        var taggedData = new Data(data, NextId.IncrementAndGet());

        _entities.AddOrUpdate(data.Id, taggedData, (k, value) => value);

        return(Xoom.Common.Completes.WithSuccess(Response.Of(ResponseStatus.Created,
                                                             JsonSerialization.Serialized(taggedData))));
    }
Пример #5
0
            public CounterHolder(int times)
            {
                var counter = new AtomicInteger(0);

                _safely = AccessSafely
                          .AfterCompleting(times)
                          .WritingWith <int>("counter", _ => counter.IncrementAndGet())
                          .ReadingWith("counter", counter.Get);
            }
Пример #6
0
            public override bool IncrementToken()
            {
                bool hasNext = input.IncrementToken();

                if (hasNext)
                {
                    PayloadAtt.Payload = new BytesRef(new[] { (byte)PayloadCount.IncrementAndGet() });
                }
                return(hasNext);
            }
Пример #7
0
        /// <summary>Increment the reference count.</summary>
        /// <exception cref="ClosedChannelException">If the status is closed.</exception>
        public virtual void Reference()
        {
            int curBits = status.IncrementAndGet();

            if ((curBits & StatusClosedMask) != 0)
            {
                status.DecrementAndGet();
                throw new ClosedChannelException();
            }
        }
Пример #8
0
        public void TestNoDeclareWithCachedConnections()
        {
            var services = new ServiceCollection();
            var config   = new ConfigurationBuilder().Build();

            services.AddLogging(b =>
            {
                b.AddDebug();
                b.AddConsole();
            });

            services.AddSingleton <IConfiguration>(config);
            services.AddRabbitHostingServices();

            var mockConnectionFactory = new Mock <RC.IConnectionFactory>();

            var mockConnections  = new List <RC.IConnection>();
            var mockChannels     = new List <RC.IModel>();
            var connectionNumber = new AtomicInteger(-1);
            var channelNumber    = new AtomicInteger(-1);

            mockConnectionFactory.Setup(f => f.CreateConnection(It.IsAny <string>()))
            .Callback(() =>
            {
                var connection    = new Mock <RC.IConnection>();
                var connectionNum = connectionNumber.IncrementAndGet();
                mockConnections.Add(connection.Object);
                connection.Setup(c => c.IsOpen).Returns(true);
                connection.Setup(c => c.ToString()).Returns("mockConnection" + connectionNum);
                connection.Setup(c => c.CreateModel())
                .Callback(() =>
                {
                    var channel = new Mock <RC.IModel>();
                    mockChannels.Add(channel.Object);
                    channel.Setup(c => c.IsOpen).Returns(true);
                    var channelNum = channelNumber.IncrementAndGet();
                    channel.Setup(c => c.ToString()).Returns("mockChannel" + channelNum);
                })
                .Returns(() => mockChannels[channelNumber.Value]);
            })
            .Returns(() => mockConnections[connectionNumber.Value]);

            var ccf   = new CachingConnectionFactory(mockConnectionFactory.Object, false, CachingConnectionFactory.CachingMode.CONNECTION);
            var queue = new Queue("foo");

            services.AddRabbitQueue(queue);
            var provider = services.BuildServiceProvider();
            var context  = provider.GetApplicationContext();
            var admin    = new RabbitAdmin(context, ccf);

            ccf.CreateConnection().Close();
            ccf.Destroy();
            Assert.Empty(mockChannels);
        }
Пример #9
0
        /// <summary>
        /// Note: Document instance is re-used per-thread </summary>
        public virtual Document NextDoc()
        {
            string line;

            lock (this)
            {
                line = Reader.ReadLine();
                if (line == null)
                {
                    // Always rewind at end:
                    if (LuceneTestCase.VERBOSE)
                    {
                        Console.WriteLine("TEST: LineFileDocs: now rewind file...");
                    }
                    Dispose();
                    Open(null);
                    line = Reader.ReadLine();
                }
            }

            DocState docState = ThreadDocs.Value;

            if (docState == null)
            {
                docState         = new DocState(UseDocValues);
                ThreadDocs.Value = docState;
            }

            int spot = line.IndexOf(SEP);

            if (spot == -1)
            {
                throw new Exception("line: [" + line + "] is in an invalid format !");
            }
            int spot2 = line.IndexOf(SEP, 1 + spot);

            if (spot2 == -1)
            {
                throw new Exception("line: [" + line + "] is in an invalid format !");
            }

            docState.Body.StringValue = line.Substring(1 + spot2, line.Length - (1 + spot2));
            string title = line.Substring(0, spot);

            docState.Title.StringValue = title;
            if (docState.TitleDV != null)
            {
                docState.TitleDV.BytesValue = new BytesRef(title);
            }
            docState.TitleTokenized.StringValue = title;
            docState.Date.StringValue           = line.Substring(1 + spot, spot2 - (1 + spot));
            docState.Id.StringValue             = Convert.ToString(Id.IncrementAndGet());
            return(docState.Doc);
        }
Пример #10
0
            internal virtual Future <byte[]> SubmitAllocate()
            {
                count.IncrementAndGet();
                Future <byte[]> f = pool.Submit(new _Callable_438(this));

                lock (arrays)
                {
                    arrays.AddItem(f);
                }
                return(f);
            }
Пример #11
0
        public void Add(T data)
        {
            if (_data.Length == 0)
            {
                return;
            }

            int index = (_count.IncrementAndGet() - 1) % _data.Length;

            _data[index] = data;
        }
Пример #12
0
 public MockCompletes(int times)
     : base((Scheduler)null)
 {
     _safely = AccessSafely.AfterCompleting(times)
               .WritingWith <T>("outcome", val =>
     {
         _outcome.Set(val);
         _withCount.IncrementAndGet();
     })
               .ReadingWith("outcome", _outcome.Get)
               .ReadingWith("count", _withCount.Get);
 }
Пример #13
0
            public ScanResult(int times)
            {
                var foundCount    = new AtomicInteger(0);
                var notFoundCount = new AtomicInteger(0);

                safely = AccessSafely
                         .AfterCompleting(times)
                         .WritingWith <int>("foundCount", _ => foundCount.IncrementAndGet())
                         .ReadingWith("foundCount", foundCount.Get)
                         .WritingWith <int>("notFoundCount", _ => notFoundCount.IncrementAndGet())
                         .ReadingWith("notFoundCount", notFoundCount.Get);
            }
Пример #14
0
        public bool TryAcquire()
        {
            int count = UsedCount.IncrementAndGet();

            if (count > Count)
            {
                UsedCount.DecrementAndGet();
                return(false);
            }

            return(true);
        }
Пример #15
0
        /// <summary>
        /// 获取订单流水号。
        /// 生成方式:日期+long(商家ID+订单类型+主机ID+AtomicInteger)
        /// 实现方式:通过位移与或运算
        /// 符号位(1)+当前秒数(17)+商家ID(14)+订单类型(4)+服务器ID(4)+AtomichInteger(24)
        /// 参考:http://www.cnblogs.com/nele/p/7882071.html
        /// </summary>
        /// <param name="mechId">商户ID</param>
        /// <param name="type">订单类型</param>
        /// <returns></returns>
        public static string Next(long mechId, long type)
        {
            long second      = ToSeconds() - ToSeconds(DateTime.Now.BeginOfDay());
            long serverId    = 1;//这个地方可以根据服务器参数来设置的
            long serial      = Serial.IncrementAndGet();
            long secondShift = second << (64 - 1 - ShiftsForTimestamp);
            long unionShift  = mechId << (64 - 1 - ShiftsForTimestamp - ShiftsForUnion);
            long typeShift   = type << (64 - 1 - ShiftsForTimestamp - ShiftsForUnion - ShiftsForType);
            long nodeShift   = serverId << (64 - 1 - ShiftsForTimestamp - ShiftsForUnion - ShiftsForType - ShiftsForNode);
            long number      = secondShift | unionShift | typeShift | nodeShift | (serial & MaskForSerial);

            return(string.Format("{0}", DateTime.Now.ToString("yyyyMMdd") + number));
        }
Пример #16
0
 public override void Merge(MergePolicy.OneMerge merge)
 {
     if (merge.MaxNumSegments != -1 && (First || merge.Segments.Count == 1))
     {
         First = false;
         if (VERBOSE)
         {
             Console.WriteLine("TEST: maxNumSegments merge");
         }
         MergeCount.IncrementAndGet();
     }
     base.Merge(merge);
 }
        public MessageCountingResults(int times)
        {
            _access = AccessSafely.AfterCompleting(times);

            _access.WritingWith("ctor", (InstantiationType type) =>
            {
                _ctor.IncrementAndGet();
                if (type == InstantiationType.Reader)
                {
                    _readerCtor.IncrementAndGet();
                }
                else if (type == InstantiationType.Writer)
                {
                    _writerCtor.IncrementAndGet();
                }
            });
            _access.ReadingWith("ctor", () => _ctor.Get());
            _access.ReadingWith("readerCtor", () => _readerCtor.Get());
            _access.ReadingWith("writerCtor", () => _writerCtor.Get());

            _access.WritingWith("read", (string id, int totalPartitions) =>
            {
                _read.IncrementAndGet();
                var partition = PartitioningStateStore.PartitionOf(id, totalPartitions);
                _readPartitions.TryGetValue(partition, out var count);
                _readPartitions.AddOrUpdate(partition, i => 1, (x, y) => count + 1);
            });
            _access.ReadingWith("read", () => _read.Get());

            _access.WritingWith <int>("readAll", one => _readAll.IncrementAndGet());
            _access.ReadingWith("readAll", () => _readAll.Get());

            _access.WritingWith <int>("streamAllOf", one => _streamAllOf.IncrementAndGet());
            _access.ReadingWith("streamAllOf", () => _streamAllOf.Get());

            _access.WritingWith <int>("streamSomeUsing", one => _streamSomeUsing.IncrementAndGet());
            _access.ReadingWith("streamSomeUsing", () => _streamSomeUsing.Get());

            _access.WritingWith("write", (string id, int totalPartitions) =>
            {
                _write.IncrementAndGet();
                var partition = PartitioningStateStore.PartitionOf(id, totalPartitions);
                _writePartitions.TryGetValue(partition, out var count);
                _writePartitions.AddOrUpdate(partition, i => 1, (x, y) => count + 1);
            });
            _access.ReadingWith("write", () => _write.Get());

            _access.WritingWith <int>("entryReader", one => _entryReader.IncrementAndGet());
            _access.ReadingWith("entryReader", () => _entryReader.Get());
        }
        public void TestAlwaysAccessible()
        {
            var pool  = new ByteBufferPool(1, 100);
            var count = new AtomicInteger(0);

            var work1 = new Thread(() =>
            {
                for (int c = 0; c < 10_000_000; ++c)
                {
                    var pooled = pool.Access();
                    pooled.Clear().Put(Converters.TextToBytes("I got it: 1!")).Flip();
                    pooled.Release();
                }

                count.IncrementAndGet();
            });

            var work2 = new Thread(() =>
            {
                for (int c = 0; c < 10_000_000; ++c)
                {
                    var pooled = pool.Access();
                    pooled.Clear().Put(Converters.TextToBytes("I got it: 2!")).Flip();
                    pooled.Release();
                }

                count.IncrementAndGet();
            });

            work1.Start();
            work2.Start();

            work1.Join();
            work2.Join();

            Assert.Equal(2, count.Get());
        }
        public ExchangeReceivers()
        {
            Access = AccessSafely.AfterCompleting(5);

            DoStepOneReceiver   = new DoStepOneReceiver(Access);
            DoStepTwoReceiver   = new DoStepTwoReceiver(Access);
            DoStepThreeReceiver = new DoStepThreeReceiver(Access);
            DoStepFourReceiver  = new DoStepFourReceiver(Access);
            DoStepFiveReceiver  = new DoStepFiveReceiver(Access);

            var stepCount = new AtomicInteger(0);

            Access.WritingWith <int>("stepCount", delta => stepCount.IncrementAndGet())
            .ReadingWith("stepCount", () => stepCount.Get());
        }
Пример #20
0
 // wait for whatever we wait on
 /// <summary>Transmit the current buffer to bookkeeper.</summary>
 /// <remarks>
 /// Transmit the current buffer to bookkeeper.
 /// Synchronised at the FSEditLog level. #write() and #setReadyToFlush()
 /// are never called at the same time.
 /// </remarks>
 /// <exception cref="System.IO.IOException"/>
 private void Transmit()
 {
     if (!transmitResult.CompareAndSet(BKException.Code.Ok, BKException.Code.Ok))
     {
         throw new IOException("Trying to write to an errored stream;" + " Error code : ("
                               + transmitResult.Get() + ") " + BKException.GetMessage(transmitResult.Get()));
     }
     if (bufCurrent.GetLength() > 0)
     {
         byte[] entry = Arrays.CopyOf(bufCurrent.GetData(), bufCurrent.GetLength());
         lh.AsyncAddEntry(entry, this, null);
         bufCurrent.Reset();
         outstandingRequests.IncrementAndGet();
     }
 }
    public AccessSafely AfterCompleting(int times)
    {
        var interestedIn       = new AtomicInteger(0);
        var informDiscovered   = new AtomicInteger(0);
        var informUnregistered = new AtomicInteger(0);

        _access = AccessSafely.AfterCompleting(times)
                  .WritingWith <int>("interestedIn", _ => interestedIn.IncrementAndGet())
                  .ReadingWith("interestedIn", () => interestedIn.Get())
                  .WritingWith <int>("informDiscovered", _ => informDiscovered.IncrementAndGet())
                  .ReadingWith("informDiscovered", () => informDiscovered.Get())
                  .WritingWith <int>("informUnregistered", _ => informUnregistered.IncrementAndGet())
                  .ReadingWith("informUnregistered", () => informUnregistered.Get());

        return(_access);
    }
Пример #22
0
 /**
  * 打开数据库
  *
  * @return SQLiteDatabase
  */
 public SQLiteDatabase openDatabase()
 {
     if (mOpenCounter.IncrementAndGet() == 1)
     {
         // Opening new database
         try
         {
             mDatabase = mDBHelper.WritableDatabase;
         }
         catch (Java.Lang.Exception)
         {
             mDatabase = mDBHelper.ReadableDatabase;
         }
     }
     return(mDatabase);
 }
Пример #23
0
        internal bool UpdateDocument(IEnumerable <IndexableField> doc, Analyzer analyzer, Term delTerm)
        {
            bool hasEvents = PreUpdate();

            ThreadState perThread = FlushControl.ObtainAndLock();

            DocumentsWriterPerThread flushingDWPT;

            try
            {
                if (!perThread.Active)
                {
                    EnsureOpen();
                    Debug.Assert(false, "perThread is not active but we are still open");
                }
                EnsureInitialized(perThread);
                Debug.Assert(perThread.Initialized);
                DocumentsWriterPerThread dwpt = perThread.Dwpt;
                int dwptNumDocs = dwpt.NumDocsInRAM;
                try
                {
                    dwpt.UpdateDocument(doc, analyzer, delTerm);
                    NumDocsInRAM.IncrementAndGet();
                }
                finally
                {
                    if (dwpt.CheckAndResetHasAborted())
                    {
                        if (dwpt.PendingFilesToDelete().Count > 0)
                        {
                            PutEvent(new DeleteNewFilesEvent(dwpt.PendingFilesToDelete()));
                        }
                        SubtractFlushedNumDocs(dwptNumDocs);
                        FlushControl.DoOnAbort(perThread);
                    }
                }
                bool isUpdate = delTerm != null;
                flushingDWPT = FlushControl.DoAfterDocument(perThread, isUpdate);
            }
            finally
            {
                perThread.Unlock();
            }

            return(PostUpdate(flushingDWPT, hasEvents));
        }
Пример #24
0
        public void TestDirectoryScan()
        {
            var scanFound = new AtomicInteger(0);

            var address1 = World.AddressFactory.UniqueWith("test-actor1");
            var address2 = World.AddressFactory.UniqueWith("test-actor2");
            var address3 = World.AddressFactory.UniqueWith("test-actor3");
            var address4 = World.AddressFactory.UniqueWith("test-actor4");
            var address5 = World.AddressFactory.UniqueWith("test-actor5");
            var address6 = World.AddressFactory.UniqueWith("test-actor6");
            var address7 = World.AddressFactory.UniqueWith("test-actor7");

            World.Stage.Directory.Register(address1, new TestInterfaceActor());
            World.Stage.Directory.Register(address2, new TestInterfaceActor());
            World.Stage.Directory.Register(address3, new TestInterfaceActor());
            World.Stage.Directory.Register(address4, new TestInterfaceActor());
            World.Stage.Directory.Register(address5, new TestInterfaceActor());

            var until = Until(7);
            Action <INoProtocol> afterConsumer = actor =>
            {
                Assert.NotNull(actor);
                scanFound.IncrementAndGet();
                until.Happened();
            };

            World.Stage.ActorOf <INoProtocol>(address5).After(afterConsumer);
            World.Stage.ActorOf <INoProtocol>(address4).After(afterConsumer);
            World.Stage.ActorOf <INoProtocol>(address3).After(afterConsumer);
            World.Stage.ActorOf <INoProtocol>(address2).After(afterConsumer);
            World.Stage.ActorOf <INoProtocol>(address1).After(afterConsumer);

            World.Stage.ActorOf <INoProtocol>(address6).After(actor =>
            {
                Assert.Null(actor);
                until.Happened();
            });
            World.Stage.ActorOf <INoProtocol>(address7).After(actor =>
            {
                Assert.Null(actor);
                until.Happened();
            });

            until.Completes();
            Assert.Equal(5, scanFound.Get());
        }
Пример #25
0
 /// <exception cref="System.Exception"/>
 protected internal virtual object PassThrough(InvocationOnMock invocation)
 {
     try
     {
         object ret = invocation.CallRealMethod();
         returnValue = ret;
         return(ret);
     }
     catch (Exception t)
     {
         thrown = t;
         throw;
     }
     finally
     {
         resultCounter.IncrementAndGet();
         resultLatch.CountDown();
     }
 }
Пример #26
0
        private void PutRunnable()
        {
            Logger.Info(Thread.CurrentThread.Name + " started.");
            int i = 0;

            while (!_stop.Get())
            {
                i++;
                // put new value and update last state
                // note: the value in the map/Near Cache is *always* larger or equal to valuePut
                // assertion: valueMap >= valuePut
                _map.Put(Key, i.ToString());
                _valuePut.Set(i);

                // check if we see our last update
                var valueMapStr = _map.Get(Key);
                if (valueMapStr == null)
                {
                    continue;
                }
                int valueMap = int.Parse(valueMapStr);
                if (valueMap != i)
                {
                    _assertionViolationCount.IncrementAndGet();
                    Logger.Warning("Assertion violated! (valueMap = " + valueMap + ", i = " + i + ")");

                    // sleep to ensure Near Cache invalidation is really lost
                    Thread.Sleep(100);

                    // test again and stop if really lost
                    valueMapStr = _map.Get(Key);
                    valueMap    = int.Parse(valueMapStr);
                    if (valueMap != i)
                    {
                        Logger.Warning("Near Cache invalidation lost! (valueMap = " + valueMap + ", i = " + i + ")");
                        _failed.Set(true);
                        _stop.Set(true);
                    }
                }
            }
            Logger.Info(Thread.CurrentThread.Name + " performed " + i + " operations.");
        }
Пример #27
0
        public void TestChangeListenerNotificationBatching()
        {
            const int numDocs       = 50;
            var       atomicInteger = new AtomicInteger(0);
            var       doneSignal    = new CountDownLatch(1);

            database.Changed += (sender, e) => atomicInteger.IncrementAndGet();

            database.RunInTransaction(() =>
            {
                CreateDocuments(database, numDocs);
                doneSignal.CountDown();
                return(true);
            });

            var success = doneSignal.Await(TimeSpan.FromSeconds(30));

            Assert.IsTrue(success);
            Assert.AreEqual(1, atomicInteger.Get());
        }
Пример #28
0
        public virtual void AddBinaryUpdate(BinaryDocValuesUpdate update, int docIDUpto)
        {
            OrderedDictionary fieldUpdates;

            if (!BinaryUpdates.TryGetValue(update.Field, out fieldUpdates))
            {
                fieldUpdates = new OrderedDictionary();
                BinaryUpdates[update.Field] = fieldUpdates;
                BytesUsed.AddAndGet(BYTES_PER_BINARY_FIELD_ENTRY);
            }

            BinaryDocValuesUpdate current = null;

            if (fieldUpdates.Contains(update.Term))
            {
                current = fieldUpdates[update.Term] as BinaryDocValuesUpdate;
            }

            if (current != null && docIDUpto < current.DocIDUpto)
            {
                // Only record the new number if it's greater than or equal to the current
                // one. this is important because if multiple threads are replacing the
                // same doc at nearly the same time, it's possible that one thread that
                // got a higher docID is scheduled before the other threads.
                return;
            }

            update.DocIDUpto = docIDUpto;
            // since it's an OrderedDictionary, we must first remove the Term entry so that
            // it's added last (we're interested in insertion-order).
            if (current != null)
            {
                fieldUpdates.Remove(update.Term);
            }
            fieldUpdates[update.Term] = update;
            NumBinaryUpdates.IncrementAndGet();
            if (current == null)
            {
                BytesUsed.AddAndGet(BYTES_PER_BINARY_UPDATE_ENTRY + update.SizeInBytes());
            }
        }
Пример #29
0
 public virtual void StartMerge(ICollection <T> inputs)
 {
     if (!closed)
     {
         numPending.IncrementAndGet();
         IList <T>       toMergeInputs = new AList <T>();
         IEnumerator <T> iter          = inputs.GetEnumerator();
         for (int ctr = 0; iter.HasNext() && ctr < mergeFactor; ++ctr)
         {
             toMergeInputs.AddItem(iter.Next());
             iter.Remove();
         }
         Log.Info(GetName() + ": Starting merge with " + toMergeInputs.Count + " segments, while ignoring "
                  + inputs.Count + " segments");
         lock (pendingToBeMerged)
         {
             pendingToBeMerged.AddLast(toMergeInputs);
             Sharpen.Runtime.NotifyAll(pendingToBeMerged);
         }
     }
 }
Пример #30
0
        public ResourceFailureTest(ITestOutputHelper output)
        {
            _output = output;
            var converter = new Converter(output);

            Console.SetOut(converter);

            _world = World.StartWithDefaults("test-request-failure");

            var resource = new FailResource(output);

            _port = NextPort.IncrementAndGet();

            _server = ServerFactory.StartWith(
                _world.Stage,
                Resources.Are(resource.Routes()),
                Filters.None(),
                _port,
                Configuration.SizingConf.DefineConf(),
                Configuration.TimingConf.DefineConf());
        }