Search in sources :

Example 21 with Cache

use of org.apache.flink.shaded.guava30.com.google.common.cache.Cache in project bookkeeper by apache.

the class TestFileInfoBackingCache method testRaceGuavaEvictAndReleaseBeforeRetain.

@Test
public void testRaceGuavaEvictAndReleaseBeforeRetain() throws Exception {
    AtomicBoolean done = new AtomicBoolean(false);
    FileInfoBackingCache cache = new FileInfoBackingCache((ledgerId, createIfNotFound) -> {
        File f = new File(baseDir, String.valueOf(ledgerId));
        f.deleteOnExit();
        return f;
    });
    Cache<Long, CachedFileInfo> guavaCache = CacheBuilder.newBuilder().maximumSize(1).removalListener(this::guavaEvictionListener).build();
    Iterable<Future<Set<CachedFileInfo>>> futures = LongStream.range(0L, 2L).mapToObj((i) -> {
        Callable<Set<CachedFileInfo>> c = () -> {
            Set<CachedFileInfo> allFileInfos = new HashSet<>();
            while (!done.get()) {
                CachedFileInfo fi = null;
                do {
                    fi = guavaCache.get(i, () -> cache.loadFileInfo(i, masterKey));
                    allFileInfos.add(fi);
                    Thread.sleep(100);
                } while (!fi.tryRetain());
                Assert.assertFalse(fi.isClosed());
                fi.release();
            }
            return allFileInfos;
        };
        return executor.submit(c);
    }).collect(Collectors.toList());
    Thread.sleep(TimeUnit.SECONDS.toMillis(10));
    done.set(true);
    // ensure all threads are finished operating on cache, before checking any
    for (Future<Set<CachedFileInfo>> f : futures) {
        f.get();
    }
    guavaCache.invalidateAll();
    for (Future<Set<CachedFileInfo>> f : futures) {
        for (CachedFileInfo fi : f.get()) {
            Assert.assertTrue(fi.isClosed());
            Assert.assertEquals(FileInfoBackingCache.DEAD_REF, fi.getRefCount());
        }
    }
}
Also used : ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder) IntStream(java.util.stream.IntStream) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Random(java.util.Random) Callable(java.util.concurrent.Callable) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Future(java.util.concurrent.Future) After(org.junit.After) ThreadFactory(java.util.concurrent.ThreadFactory) ExecutorService(java.util.concurrent.ExecutorService) Before(org.junit.Before) RemovalNotification(com.google.common.cache.RemovalNotification) LongStream(java.util.stream.LongStream) Set(java.util.Set) IOException(java.io.IOException) Test(org.junit.Test) Collectors(java.util.stream.Collectors) File(java.io.File) Executors(java.util.concurrent.Executors) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) CacheBuilder(com.google.common.cache.CacheBuilder) Cache(com.google.common.cache.Cache) Assert(org.junit.Assert) Collections(java.util.Collections) CachedFileInfo(org.apache.bookkeeper.bookie.FileInfoBackingCache.CachedFileInfo) HashSet(java.util.HashSet) Set(java.util.Set) Callable(java.util.concurrent.Callable) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CachedFileInfo(org.apache.bookkeeper.bookie.FileInfoBackingCache.CachedFileInfo) Future(java.util.concurrent.Future) File(java.io.File) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 22 with Cache

use of org.apache.flink.shaded.guava30.com.google.common.cache.Cache in project micrometer by micrometer-metrics.

the class CacheSample method main.

public static void main(String[] args) {
    MeterRegistry registry = SampleConfig.myMonitoringSystem();
    GuavaCacheMetrics.monitor(registry, guavaCache, "book.guava");
    // read all of Frankenstein
    HttpClient.create("www.gutenberg.org").get("/cache/epub/84/pg84.txt").flatMapMany(res -> res.addHandler(wordDecoder()).receive().asString()).delayElements(// one word per 10 ms
    Duration.ofMillis(10)).filter(word -> !word.isEmpty()).doOnNext(word -> {
        if (guavaCache.getIfPresent(word) == null)
            guavaCache.put(word, 1);
    }).blockLast();
}
Also used : IntStream(java.util.stream.IntStream) SampleConfig(io.micrometer.core.samples.utils.SampleConfig) ByteBuf(io.netty.buffer.ByteBuf) MeterRegistry(io.micrometer.core.instrument.MeterRegistry) Duration(java.time.Duration) HttpClient(reactor.ipc.netty.http.client.HttpClient) CacheBuilder(com.google.common.cache.CacheBuilder) Unpooled.wrappedBuffer(io.netty.buffer.Unpooled.wrappedBuffer) Cache(com.google.common.cache.Cache) DelimiterBasedFrameDecoder(io.netty.handler.codec.DelimiterBasedFrameDecoder) GuavaCacheMetrics(io.micrometer.core.instrument.binder.cache.GuavaCacheMetrics) MeterRegistry(io.micrometer.core.instrument.MeterRegistry)

Example 23 with Cache

use of org.apache.flink.shaded.guava30.com.google.common.cache.Cache in project atlasdb by palantir.

the class AtlasDbMetrics method registerCache.

public static void registerCache(Cache<?, ?> cache, String metricsPrefix) {
    MetricRegistry metricRegistry = getMetricRegistry();
    Set<String> existingMetrics = metricRegistry.getMetrics().keySet().stream().filter(name -> name.startsWith(metricsPrefix)).collect(Collectors.toSet());
    if (existingMetrics.isEmpty()) {
        MetricRegistries.registerCache(metricRegistry, cache, metricsPrefix);
    } else {
        log.info("Not registering cache with prefix '{}' as metric registry already contains metrics: {}", metricsPrefix, existingMetrics);
    }
}
Also used : Logger(org.slf4j.Logger) MetricRegistry(com.codahale.metrics.MetricRegistry) LoggerFactory(org.slf4j.LoggerFactory) Set(java.util.Set) LoggingInvocationEventHandler(com.palantir.tritium.event.log.LoggingInvocationEventHandler) SharedMetricRegistries(com.codahale.metrics.SharedMetricRegistries) DefaultTaggedMetricRegistry(com.palantir.tritium.metrics.registry.DefaultTaggedMetricRegistry) MetricRegistries(com.palantir.tritium.metrics.MetricRegistries) Instrumentation(com.palantir.tritium.proxy.Instrumentation) AtomicReference(java.util.concurrent.atomic.AtomicReference) Collectors(java.util.stream.Collectors) TaggedMetricRegistry(com.palantir.tritium.metrics.registry.TaggedMetricRegistry) MetricsInvocationEventHandler(com.palantir.tritium.event.metrics.MetricsInvocationEventHandler) LoggingLevel(com.palantir.tritium.event.log.LoggingLevel) Preconditions(com.google.common.base.Preconditions) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Cache(com.google.common.cache.Cache) MetricRegistry(com.codahale.metrics.MetricRegistry) DefaultTaggedMetricRegistry(com.palantir.tritium.metrics.registry.DefaultTaggedMetricRegistry) TaggedMetricRegistry(com.palantir.tritium.metrics.registry.TaggedMetricRegistry)

Example 24 with Cache

use of org.apache.flink.shaded.guava30.com.google.common.cache.Cache in project OpenTripPlanner by opentripplanner.

the class AnalystWorker method run.

/**
 * This is the main worker event loop which fetches tasks from a broker and schedules them for execution.
 * It maintains a small local queue on the worker so that it doesn't idle while fetching new tasks.
 */
@Override
public void run() {
    // create executors with up to one thread per processor
    int nP = Runtime.getRuntime().availableProcessors();
    highPriorityExecutor = new ThreadPoolExecutor(1, nP, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(255));
    highPriorityExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
    batchExecutor = new ThreadPoolExecutor(1, nP, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(nP * 2));
    batchExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
    // Build a graph on startup, iff a graph ID was provided.
    if (graphId != null) {
        LOG.info("Prebuilding graph {}", graphId);
        Graph graph = clusterGraphBuilder.getGraph(graphId);
        // also prebuild the stop tree cache
        graph.index.getStopTreeCache();
        LOG.info("Done prebuilding graph {}", graphId);
    }
    // Start filling the work queues.
    boolean idle = false;
    while (true) {
        long now = System.currentTimeMillis();
        // Consider shutting down if enough time has passed
        if (now > nextShutdownCheckTime && autoShutdown) {
            if (idle && now > lastHighPriorityRequestProcessed + SINGLE_POINT_KEEPALIVE) {
                LOG.warn("Machine is idle, shutting down.");
                try {
                    Process process = new ProcessBuilder("sudo", "/sbin/shutdown", "-h", "now").start();
                    process.waitFor();
                } catch (Exception ex) {
                    LOG.error("Unable to terminate worker", ex);
                } finally {
                    System.exit(0);
                }
            }
            nextShutdownCheckTime += 60 * 60 * 1000;
        }
        LOG.info("Long-polling for work ({} second timeout).", POLL_TIMEOUT / 1000.0);
        // Long-poll (wait a few seconds for messages to become available)
        List<AnalystClusterRequest> tasks = getSomeWork(WorkType.BATCH);
        if (tasks == null) {
            LOG.info("Didn't get any work. Retrying.");
            idle = true;
            continue;
        }
        // run through high-priority tasks first to ensure they are enqueued even if the batch
        // queue blocks.
        tasks.stream().filter(t -> t.outputLocation == null).forEach(t -> highPriorityExecutor.execute(() -> {
            LOG.warn("Handling single point request via normal channel, side channel should open shortly.");
            this.handleOneRequest(t);
        }));
        logQueueStatus();
        // enqueue low-priority tasks; note that this may block anywhere in the process
        tasks.stream().filter(t -> t.outputLocation != null).forEach(t -> {
            // attempt to enqueue, waiting if the queue is full
            while (true) {
                try {
                    batchExecutor.execute(() -> this.handleOneRequest(t));
                    break;
                } catch (RejectedExecutionException e) {
                    // queue is full, wait 200ms and try again
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e1) {
                    /* nothing */
                    }
                }
            }
        });
        logQueueStatus();
        idle = false;
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) SocketConfig(org.apache.http.config.SocketConfig) LoggerFactory(org.slf4j.LoggerFactory) Random(java.util.Random) RequestConfig(org.apache.http.client.config.RequestConfig) DeserializationFeature(com.fasterxml.jackson.databind.DeserializationFeature) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) EntityUtils(org.apache.http.util.EntityUtils) Graph(org.opentripplanner.routing.graph.Graph) PipedInputStream(java.io.PipedInputStream) GeoJsonModule(com.conveyal.geojson.GeoJsonModule) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) URI(java.net.URI) TypeReference(com.fasterxml.jackson.core.type.TypeReference) MavenVersion(org.opentripplanner.common.MavenVersion) HttpEntity(org.apache.http.HttpEntity) AgencyAndIdSerializer(org.opentripplanner.api.model.AgencyAndIdSerializer) AmazonS3Client(com.amazonaws.services.s3.AmazonS3Client) UUID(java.util.UUID) RepeatedRaptorProfileRouter(org.opentripplanner.profile.RepeatedRaptorProfileRouter) RaptorWorkerData(org.opentripplanner.profile.RaptorWorkerData) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) List(java.util.List) HttpGet(org.apache.http.client.methods.HttpGet) GZIPOutputStream(java.util.zip.GZIPOutputStream) CacheBuilder(com.google.common.cache.CacheBuilder) HttpClients(org.apache.http.impl.client.HttpClients) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) JodaLocalDateSerializer(org.opentripplanner.api.model.JodaLocalDateSerializer) LocalDateTime(java.time.LocalDateTime) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) Regions(com.amazonaws.regions.Regions) HttpDelete(org.apache.http.client.methods.HttpDelete) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) HttpClient(org.apache.http.client.HttpClient) QualifiedModeSetSerializer(org.opentripplanner.api.model.QualifiedModeSetSerializer) SocketTimeoutException(java.net.SocketTimeoutException) AmazonS3(com.amazonaws.services.s3.AmazonS3) TraverseModeSetSerializer(org.opentripplanner.api.model.TraverseModeSetSerializer) PointSet(org.opentripplanner.analyst.PointSet) OutputStream(java.io.OutputStream) Logger(org.slf4j.Logger) Properties(java.util.Properties) JsonParser(com.fasterxml.jackson.core.JsonParser) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) R5Main(com.conveyal.r5.R5Main) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) PipedOutputStream(java.io.PipedOutputStream) InputStreamReader(java.io.InputStreamReader) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) BasicHeader(org.apache.http.message.BasicHeader) DateTimeFormatter(java.time.format.DateTimeFormatter) HttpResponse(org.apache.http.HttpResponse) SampleSet(org.opentripplanner.analyst.SampleSet) BufferedReader(java.io.BufferedReader) Region(com.amazonaws.regions.Region) Cache(com.google.common.cache.Cache) InputStream(java.io.InputStream) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) SocketTimeoutException(java.net.SocketTimeoutException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) Graph(org.opentripplanner.routing.graph.Graph) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor)

Example 25 with Cache

use of org.apache.flink.shaded.guava30.com.google.common.cache.Cache in project free-framework by a601942905git.

the class CacheTest1 method main.

public static void main(String[] args) throws ExecutionException, InterruptedException {
    CacheData cacheData = new CacheData();
    Cache cache = CacheBuilder.newBuilder().build();
    List<CacheEntity> cacheEntityList = (List<CacheEntity>) cache.get(CACHE_ENTITY_KEY, () -> cacheData.getCacheList());
    cacheEntityList.stream().forEach(System.out::println);
    System.out.println(cache.size());
    System.out.println("沉睡2s");
    Thread.sleep(2000);
    System.out.println("苏醒");
    cacheEntityList = (List<CacheEntity>) cache.get(CACHE_ENTITY_KEY, () -> cacheData.getCacheList());
    cacheEntityList.stream().forEach(System.out::println);
    System.out.println(cache.size());
    cache.put("key1", "value1");
    System.out.println(cache.size());
}
Also used : List(java.util.List) Cache(com.google.common.cache.Cache)

Aggregations

Cache (com.google.common.cache.Cache)38 List (java.util.List)18 CacheBuilder (com.google.common.cache.CacheBuilder)17 Optional (java.util.Optional)10 MILLISECONDS (java.util.concurrent.TimeUnit.MILLISECONDS)10 Module (com.google.inject.Module)9 TimeUnit (java.util.concurrent.TimeUnit)9 Collectors (java.util.stream.Collectors)9 CachingOrcFileTailSource (com.facebook.presto.orc.cache.CachingOrcFileTailSource)8 OrcFileTailSource (com.facebook.presto.orc.cache.OrcFileTailSource)8 StorageOrcFileTailSource (com.facebook.presto.orc.cache.StorageOrcFileTailSource)8 OrcFileTail (com.facebook.presto.orc.metadata.OrcFileTail)8 RowGroupIndex (com.facebook.presto.orc.metadata.RowGroupIndex)8 ArrayList (java.util.ArrayList)8 ExecutorService (java.util.concurrent.ExecutorService)8 ConfigBinder.configBinder (com.facebook.airlift.configuration.ConfigBinder.configBinder)7 CachingStripeMetadataSource (com.facebook.presto.orc.CachingStripeMetadataSource)7 DwrfAwareStripeMetadataSourceFactory (com.facebook.presto.orc.DwrfAwareStripeMetadataSourceFactory)7 OrcDataSourceId (com.facebook.presto.orc.OrcDataSourceId)7 StorageStripeMetadataSource (com.facebook.presto.orc.StorageStripeMetadataSource)7