Search in sources :

Example 26 with LongSummaryStatistics

use of java.util.LongSummaryStatistics in project lucene-solr by apache.

the class TestDocValuesStatsCollector method testDocsWithMultipleLongValues.

public void testDocsWithMultipleLongValues() throws IOException {
    try (Directory dir = newDirectory();
        IndexWriter indexWriter = new IndexWriter(dir, newIndexWriterConfig())) {
        String field = "numeric";
        int numDocs = TestUtil.nextInt(random(), 1, 100);
        long[][] docValues = new long[numDocs][];
        long nextVal = 1;
        for (int i = 0; i < numDocs; i++) {
            Document doc = new Document();
            if (random().nextBoolean()) {
                // not all documents have a value
                int numValues = TestUtil.nextInt(random(), 1, 5);
                docValues[i] = new long[numValues];
                for (int j = 0; j < numValues; j++) {
                    doc.add(new SortedNumericDocValuesField(field, nextVal));
                    docValues[i][j] = nextVal;
                    ++nextVal;
                }
                doc.add(new StringField("id", "doc" + i, Store.NO));
            }
            indexWriter.addDocument(doc);
        }
        // 20% of cases delete some docs
        if (random().nextDouble() < 0.2) {
            for (int i = 0; i < numDocs; i++) {
                if (random().nextBoolean()) {
                    indexWriter.deleteDocuments(new Term("id", "doc" + i));
                    docValues[i] = null;
                }
            }
        }
        try (DirectoryReader reader = DirectoryReader.open(indexWriter)) {
            IndexSearcher searcher = new IndexSearcher(reader);
            SortedLongDocValuesStats stats = new SortedLongDocValuesStats(field);
            searcher.search(new MatchAllDocsQuery(), new DocValuesStatsCollector(stats));
            assertEquals(nonNull(docValues).count(), stats.count());
            int numDocsWithoutField = (int) isNull(docValues).count();
            assertEquals(computeExpMissing(numDocsWithoutField, numDocs, reader), stats.missing());
            if (stats.count() > 0) {
                LongSummaryStatistics sumStats = filterAndFlatValues(docValues, (v) -> v != null).summaryStatistics();
                assertEquals(sumStats.getMax(), stats.max().longValue());
                assertEquals(sumStats.getMin(), stats.min().longValue());
                assertEquals(sumStats.getAverage(), stats.mean(), 0.00001);
                assertEquals(sumStats.getSum(), stats.sum().longValue());
                assertEquals(sumStats.getCount(), stats.valuesCount());
                double variance = computeVariance(filterAndFlatValues(docValues, (v) -> v != null), stats.mean, stats.count());
                assertEquals(variance, stats.variance(), 0.00001);
                assertEquals(Math.sqrt(variance), stats.stdev(), 0.00001);
            }
        }
    }
}
Also used : Arrays(java.util.Arrays) DoubleDocValuesStats(org.apache.lucene.search.DocValuesStats.DoubleDocValuesStats) StringField(org.apache.lucene.document.StringField) SortedNumericDocValuesField(org.apache.lucene.document.SortedNumericDocValuesField) Term(org.apache.lucene.index.Term) TestUtil(org.apache.lucene.util.TestUtil) DoubleSummaryStatistics(java.util.DoubleSummaryStatistics) SortedSetDocValuesStats(org.apache.lucene.search.DocValuesStats.SortedSetDocValuesStats) Document(org.apache.lucene.document.Document) SortedDocValuesStats(org.apache.lucene.search.DocValuesStats.SortedDocValuesStats) Directory(org.apache.lucene.store.Directory) Store(org.apache.lucene.document.Field.Store) LongSummaryStatistics(java.util.LongSummaryStatistics) SortedDoubleDocValuesStats(org.apache.lucene.search.DocValuesStats.SortedDoubleDocValuesStats) DoubleDocValuesField(org.apache.lucene.document.DoubleDocValuesField) NumericDocValuesField(org.apache.lucene.document.NumericDocValuesField) LongStream(java.util.stream.LongStream) SortedSetDocValuesField(org.apache.lucene.document.SortedSetDocValuesField) Predicate(java.util.function.Predicate) BytesRef(org.apache.lucene.util.BytesRef) DirectoryReader(org.apache.lucene.index.DirectoryReader) IOException(java.io.IOException) LongDocValuesStats(org.apache.lucene.search.DocValuesStats.LongDocValuesStats) DoubleStream(java.util.stream.DoubleStream) Objects(java.util.Objects) IndexWriter(org.apache.lucene.index.IndexWriter) Stream(java.util.stream.Stream) SortedDocValuesField(org.apache.lucene.document.SortedDocValuesField) LuceneTestCase(org.apache.lucene.util.LuceneTestCase) SortedLongDocValuesStats(org.apache.lucene.search.DocValuesStats.SortedLongDocValuesStats) IndexReader(org.apache.lucene.index.IndexReader) DirectoryReader(org.apache.lucene.index.DirectoryReader) Term(org.apache.lucene.index.Term) Document(org.apache.lucene.document.Document) LongSummaryStatistics(java.util.LongSummaryStatistics) SortedNumericDocValuesField(org.apache.lucene.document.SortedNumericDocValuesField) IndexWriter(org.apache.lucene.index.IndexWriter) StringField(org.apache.lucene.document.StringField) SortedLongDocValuesStats(org.apache.lucene.search.DocValuesStats.SortedLongDocValuesStats) Directory(org.apache.lucene.store.Directory)

Example 27 with LongSummaryStatistics

use of java.util.LongSummaryStatistics in project nifi by apache.

the class ThreadPoolRequestReplicator method logTimingInfo.

private void logTimingInfo(final AsyncClusterResponse response) {
    // Calculate min, max, mean for the requests
    final LongSummaryStatistics stats = response.getNodesInvolved().stream().map(p -> response.getNodeResponse(p).getRequestDuration(TimeUnit.MILLISECONDS)).collect(Collectors.summarizingLong(Long::longValue));
    final StringBuilder sb = new StringBuilder();
    sb.append("Node Responses for ").append(response.getMethod()).append(" ").append(response.getURIPath()).append(" (Request ID ").append(response.getRequestIdentifier()).append("):\n");
    for (final NodeIdentifier node : response.getNodesInvolved()) {
        sb.append(node).append(": ").append(response.getNodeResponse(node).getRequestDuration(TimeUnit.MILLISECONDS)).append(" millis\n");
    }
    logger.debug("For {} {} (Request ID {}), minimum response time = {}, max = {}, average = {} ms", response.getMethod(), response.getURIPath(), response.getRequestIdentifier(), stats.getMin(), stats.getMax(), stats.getAverage());
    logger.debug(sb.toString());
}
Also used : LongSummaryStatistics(java.util.LongSummaryStatistics) NodeIdentifier(org.apache.nifi.cluster.protocol.NodeIdentifier) DisconnectedNodeMutableRequestException(org.apache.nifi.cluster.manager.exception.DisconnectedNodeMutableRequestException) URISyntaxException(java.net.URISyntaxException) LoggerFactory(org.slf4j.LoggerFactory) UriConstructionException(org.apache.nifi.cluster.manager.exception.UriConstructionException) StringUtils(org.apache.commons.lang3.StringUtils) MediaType(javax.ws.rs.core.MediaType) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) URI(java.net.URI) ThreadFactory(java.util.concurrent.ThreadFactory) NodeResponse(org.apache.nifi.cluster.manager.NodeResponse) ReadWriteLock(java.util.concurrent.locks.ReadWriteLock) ComponentIdGenerator(org.apache.nifi.util.ComponentIdGenerator) HttpHeaders(org.apache.nifi.remote.protocol.http.HttpHeaders) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HttpResponseMapper(org.apache.nifi.cluster.coordination.http.HttpResponseMapper) Set(java.util.Set) ClientProperties(org.glassfish.jersey.client.ClientProperties) Invocation(javax.ws.rs.client.Invocation) UUID(java.util.UUID) EncodingFilter(org.glassfish.jersey.client.filter.EncodingFilter) StandardHttpResponseMapper(org.apache.nifi.cluster.coordination.http.StandardHttpResponseMapper) ProxiedEntitiesUtils(org.apache.nifi.web.security.ProxiedEntitiesUtils) Entity(javax.ws.rs.client.Entity) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) Collectors(java.util.stream.Collectors) Executors(java.util.concurrent.Executors) Objects(java.util.Objects) List(java.util.List) GZipEncoder(org.glassfish.jersey.message.GZipEncoder) Stream(java.util.stream.Stream) Response(javax.ws.rs.core.Response) IllegalClusterStateException(org.apache.nifi.cluster.manager.exception.IllegalClusterStateException) Entry(java.util.Map.Entry) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) NoConnectedNodesException(org.apache.nifi.cluster.manager.exception.NoConnectedNodesException) Client(javax.ws.rs.client.Client) AccessDeniedException(org.apache.nifi.authorization.AccessDeniedException) HashMap(java.util.HashMap) ConnectingNodeMutableRequestException(org.apache.nifi.cluster.manager.exception.ConnectingNodeMutableRequestException) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) Function(java.util.function.Function) HttpMethod(javax.ws.rs.HttpMethod) ConcurrentMap(java.util.concurrent.ConcurrentMap) HashSet(java.util.HashSet) NiFiUser(org.apache.nifi.authorization.user.NiFiUser) ClusterCoordinator(org.apache.nifi.cluster.coordination.ClusterCoordinator) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) NodeConnectionState(org.apache.nifi.cluster.coordination.node.NodeConnectionState) Status(javax.ws.rs.core.Response.Status) NodeConnectionStatus(org.apache.nifi.cluster.coordination.node.NodeConnectionStatus) LongSummaryStatistics(java.util.LongSummaryStatistics) JwtAuthenticationFilter(org.apache.nifi.web.security.jwt.JwtAuthenticationFilter) Logger(org.slf4j.Logger) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) TimeUnit(java.util.concurrent.TimeUnit) Lock(java.util.concurrent.locks.Lock) EventReporter(org.apache.nifi.events.EventReporter) FormatUtils(org.apache.nifi.util.FormatUtils) NiFiProperties(org.apache.nifi.util.NiFiProperties) NiFiUserUtils(org.apache.nifi.authorization.user.NiFiUserUtils) Severity(org.apache.nifi.reporting.Severity) UnknownNodeException(org.apache.nifi.cluster.manager.exception.UnknownNodeException) WebTarget(javax.ws.rs.client.WebTarget) Collections(java.util.Collections) NodeIdentifier(org.apache.nifi.cluster.protocol.NodeIdentifier)

Example 28 with LongSummaryStatistics

use of java.util.LongSummaryStatistics in project hono by eclipse.

the class SendReceiveIT method testTelemetryUpload.

/**
 * Verifies that telemetry messages uploaded to the Hono server are all received
 * by a downstream consumer.
 *
 * @throws Exception if the test fails.
 */
@Test
public void testTelemetryUpload() throws Exception {
    givenAReceiver();
    givenASender();
    getRegistrationClient().register(DEVICE_ID, Duration.ofMillis(DEFAULT_TEST_TIMEOUT));
    final CountDownLatch latch = new CountDownLatch(IntegrationTestSupport.MSG_COUNT);
    final LongSummaryStatistics stats = new LongSummaryStatistics();
    // get registration assertion
    final String registrationAssertion = getRegistrationAssertion(DEVICE_ID);
    // prepare consumer
    final MessageConsumer messageConsumer = receiver.getTelemetryConsumer();
    messageConsumer.setMessageListener(message -> {
        latch.countDown();
        gatherStatistics(stats, message);
        if (LOG.isTraceEnabled()) {
            final long messagesReceived = IntegrationTestSupport.MSG_COUNT - latch.getCount();
            if (messagesReceived % 100 == 0) {
                LOG.trace("Received {} messages.", messagesReceived);
            }
        }
    });
    final MessageProducer messageProducer = sender.getTelemetryProducer();
    IntStream.range(0, IntegrationTestSupport.MSG_COUNT).forEach(i -> {
        try {
            final Message message = sender.newMessage("msg " + i, DEVICE_ID, registrationAssertion);
            messageProducer.send(message, DELIVERY_MODE, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE);
            if (LOG.isTraceEnabled() && i > 0 && i % 100 == 0) {
                LOG.trace("Sent message {}", i);
            }
        } catch (final JMSException e) {
            LOG.error("Error occurred while sending message: {}", e.getMessage(), e);
        }
    });
    long timeToWait = Math.max(DEFAULT_TEST_TIMEOUT, Math.round(IntegrationTestSupport.MSG_COUNT * 1.2));
    // wait for messages to arrive
    assertTrue("did not receive all " + IntegrationTestSupport.MSG_COUNT + " messages", latch.await(timeToWait, TimeUnit.MILLISECONDS));
    LOG.info("Delivery statistics: {}", stats);
}
Also used : LongSummaryStatistics(java.util.LongSummaryStatistics) MessageConsumer(javax.jms.MessageConsumer) Message(javax.jms.Message) JMSException(javax.jms.JMSException) MessageProducer(javax.jms.MessageProducer) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test)

Example 29 with LongSummaryStatistics

use of java.util.LongSummaryStatistics in project xian by happyyangyuan.

the class DistributedLockTest method QPS.

@Test
public void QPS() {
    final CountDownLatch startCountDownLatch = new CountDownLatch(1);
    final int number = 1000;
    final CountDownLatch finishCountDownLatch = new CountDownLatch(number);
    final List<Long> consumeTimes = new CopyOnWriteArrayList<>();
    for (int i = 0; i < number; i++) {
        int _i = i;
        ThreadPoolManager.execute(() -> {
            try {
                startCountDownLatch.await();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            long startTime = System.nanoTime();
            // Redis Lock
            DistributedLockSynchronizer.call("QPS_" + _i, 3, () -> {
                return null;
            }, 3);
            // ZK Lock
            // try
            // {
            // Synchronizer.call("QPS_" + _i, () -> {
            // return null;
            // }, 3L);
            // }
            // catch (Exception e)
            // {
            // LOG.error(e);
            // }
            finishCountDownLatch.countDown();
            long endTime = System.nanoTime();
            consumeTimes.add(endTime - startTime);
        });
    }
    try {
        startCountDownLatch.countDown();
        finishCountDownLatch.await();
        long totalConsumeTime = 0;
        for (long consumeTime : consumeTimes) totalConsumeTime += consumeTime;
        long avgConsumeTime = totalConsumeTime / number;
        LongSummaryStatistics intSummaryStatistics = consumeTimes.stream().collect(Collectors.summarizingLong(value -> value));
        LOG.info(String.format("QPS, 加锁解锁, 任务数量: %s, 累计耗时: %s, %s, 平均耗时:%s, %s, %s", number, totalConsumeTime, totalConsumeTime / 1000000, avgConsumeTime, avgConsumeTime / 1000000, intSummaryStatistics));
    } catch (Exception e) {
        LOG.error(e);
    }
    UnitResponse unitResponseObject = Xian.call(CacheService.CACHE_SERVICE, "cacheKeys", new JSONObject() {

        {
            put("pattern", "LOCK_QPS_*");
        }
    });
    if (unitResponseObject.succeeded() && unitResponseObject.getData() != null) {
        Set<String> keys = unitResponseObject.getData();
        LOG.info(String.format("分布锁剩余数量: %s", keys.size()));
    }
    Xian.call("diyMonitor", "jedisLockMonitor", new JSONObject());
}
Also used : Xian(info.xiancloud.core.message.Xian) Set(java.util.Set) UnitResponse(info.xiancloud.core.message.UnitResponse) Test(org.junit.Test) Collectors(java.util.stream.Collectors) EnvUtil(info.xiancloud.core.util.EnvUtil) CacheService(info.xiancloud.core.support.cache.CacheService) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) ThreadPoolManager(info.xiancloud.core.thread_pool.ThreadPoolManager) DistributedLockSynchronizer(info.xiancloud.core.support.cache.lock.DistributedLockSynchronizer) After(org.junit.After) JSONObject(com.alibaba.fastjson.JSONObject) XianConfig(info.xiancloud.core.conf.XianConfig) LOG(info.xiancloud.core.util.LOG) LongSummaryStatistics(java.util.LongSummaryStatistics) Before(org.junit.Before) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) CountDownLatch(java.util.concurrent.CountDownLatch) LongSummaryStatistics(java.util.LongSummaryStatistics) JSONObject(com.alibaba.fastjson.JSONObject) UnitResponse(info.xiancloud.core.message.UnitResponse) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) Test(org.junit.Test)

Example 30 with LongSummaryStatistics

use of java.util.LongSummaryStatistics in project xian by happyyangyuan.

the class JedisTestDistributedLock method execute.

@Override
public UnitResponse execute(UnitRequest msg) {
    int number = msg.get("number", int.class, 10000);
    final CountDownLatch startCountDownLatch = new CountDownLatch(1);
    final CountDownLatch finishCountDownLatch = new CountDownLatch(number);
    final List<Long> consumeTimes = new CopyOnWriteArrayList<>();
    for (int i = 0; i < number; i++) {
        int _i = i;
        ThreadPoolManager.execute(() -> {
            try {
                startCountDownLatch.await();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            long startTime = System.nanoTime();
            // Redis Lock
            DistributedLockSynchronizer.call("QPS_" + _i, 3, () -> {
                return null;
            }, 3);
            // ZK Lock
            // try
            // {
            // Synchronizer.call("QPS_" + _i, () -> {
            // return null;
            // }, 3L);
            // }
            // catch (Exception e)
            // {
            // LOG.error(e);
            // }
            finishCountDownLatch.countDown();
            long endTime = System.nanoTime();
            consumeTimes.add(endTime - startTime);
        });
    }
    try {
        startCountDownLatch.countDown();
        finishCountDownLatch.await();
    } catch (Exception e) {
        LOG.error(e);
    }
    long totalConsumeTime = 0;
    for (long consumeTime : consumeTimes) totalConsumeTime += consumeTime;
    long avgConsumeTime = totalConsumeTime / number;
    LongSummaryStatistics intSummaryStatistics = consumeTimes.stream().collect(Collectors.summarizingLong(value -> value));
    String log = String.format("QPS, 加锁解锁, 任务数量: %s, 累计耗时: %s, %s, 平均耗时:%s, %s, %s", number, totalConsumeTime, totalConsumeTime / 1000000, avgConsumeTime, avgConsumeTime / 1000000, intSummaryStatistics);
    LOG.info(log);
    UnitResponse unitResponseObject = SyncXian.call("cache", "cacheKeys", new JSONObject() {

        {
            put("pattern", "LOCK_QPS_*");
        }
    });
    if (unitResponseObject.succeeded() && unitResponseObject.getData() != null) {
        Set<String> keys = unitResponseObject.getData();
        LOG.info(String.format("分布锁剩余数量: %s", keys.size()));
    }
    SyncXian.call("diyMonitor", "jedisLockMonitor", new JSONObject() {

        {
        }
    });
    return UnitResponse.success(log);
}
Also used : Group(info.xiancloud.core.Group) Unit(info.xiancloud.core.Unit) SyncXian(info.xiancloud.core.message.SyncXian) UnitRequest(info.xiancloud.core.message.UnitRequest) CacheGroup(info.xiancloud.cache.service.CacheGroup) Set(java.util.Set) UnitResponse(info.xiancloud.core.message.UnitResponse) Collectors(java.util.stream.Collectors) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Input(info.xiancloud.core.Input) ThreadPoolManager(info.xiancloud.core.thread_pool.ThreadPoolManager) DistributedLockSynchronizer(info.xiancloud.core.support.cache.lock.DistributedLockSynchronizer) JSONObject(com.alibaba.fastjson.JSONObject) LOG(info.xiancloud.core.util.LOG) UnitMeta(info.xiancloud.core.UnitMeta) LongSummaryStatistics(java.util.LongSummaryStatistics) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) CountDownLatch(java.util.concurrent.CountDownLatch) LongSummaryStatistics(java.util.LongSummaryStatistics) JSONObject(com.alibaba.fastjson.JSONObject) UnitResponse(info.xiancloud.core.message.UnitResponse) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList)

Aggregations

LongSummaryStatistics (java.util.LongSummaryStatistics)47 Test (org.junit.Test)18 List (java.util.List)15 Map (java.util.Map)12 CountDownLatch (java.util.concurrent.CountDownLatch)11 ArrayList (java.util.ArrayList)10 Collectors (java.util.stream.Collectors)10 Set (java.util.Set)9 TimeUnit (java.util.concurrent.TimeUnit)9 LoggerFactory (org.slf4j.LoggerFactory)9 HashMap (java.util.HashMap)8 Logger (org.slf4j.Logger)8 BaseTest (io.scalecube.testlib.BaseTest)7 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)6 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)6 Arrays (java.util.Arrays)5 Stream (java.util.stream.Stream)5 Collections (java.util.Collections)4 Comparator (java.util.Comparator)4 Entry (java.util.Map.Entry)4