Java Code Examples for com.google.common.cache.CacheBuilder

The following examples show how to use com.google.common.cache.CacheBuilder. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: registry   Source File: SchemaMetadataCache.java    License: Apache License 2.0 6 votes vote down vote up
public SchemaMetadataCache(Long size, Long expiryInSecs, final SchemaMetadataFetcher schemaMetadataFetcher) {
    schemaNameToIdMap = Maps.synchronizedBiMap(HashBiMap.create());
    loadingCache = CacheBuilder.newBuilder()
            .maximumSize(size)
            .expireAfterAccess(expiryInSecs, TimeUnit.SECONDS)
            .build(new CacheLoader<Key, SchemaMetadataInfo>() {
                @Override
                public SchemaMetadataInfo load(Key key) throws Exception {
                    SchemaMetadataInfo schemaMetadataInfo;
                    Key otherKey;
                    if (key.getName() != null) {
                        schemaMetadataInfo = schemaMetadataFetcher.fetch(key.getName());
                        otherKey = Key.of(schemaMetadataInfo.getId());
                        schemaNameToIdMap.put(key.getName(), schemaMetadataInfo.getId());
                    } else if (key.getId() != null) {
                        schemaMetadataInfo = schemaMetadataFetcher.fetch(key.getId());
                        otherKey = Key.of(schemaMetadataInfo.getSchemaMetadata().getName());
                        schemaNameToIdMap.put(schemaMetadataInfo.getSchemaMetadata().getName(), schemaMetadataInfo.getId());
                    } else {
                        throw new RegistryException("Key should have name or id as non null");
                    }
                    loadingCache.put(otherKey, schemaMetadataInfo);
                    return schemaMetadataInfo;
                }
            });
}
 
Example 2
Source Project: flowable-engine   Source File: FlowableCookieFilter.java    License: Apache License 2.0 6 votes vote down vote up
protected void initUserCache() {
    FlowableCommonAppProperties.Cache cache = properties.getCacheLoginUsers();
    Long userMaxSize = cache.getMaxSize();
    Long userMaxAge = cache.getMaxAge();
    userCache = CacheBuilder.newBuilder().maximumSize(userMaxSize).expireAfterWrite(userMaxAge, TimeUnit.SECONDS).recordStats()
            .build(new CacheLoader<String, FlowableAppUser>() {

                @Override
                public FlowableAppUser load(final String userId) throws Exception {
                    RemoteUser user = remoteIdmService.getUser(userId);
                    if (user == null) {
                        throw new FlowableException("user not found " + userId);
                    }

                    Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>();
                    for (String privilege : user.getPrivileges()) {
                        grantedAuthorities.add(new SimpleGrantedAuthority(privilege));
                    }

                    // put account into security context (for controllers to use)
                    FlowableAppUser appUser = new FlowableAppUser(user, user.getId(), grantedAuthorities);
                    return appUser;
                }

            });
}
 
Example 3
@Inject
public NetflowV9CodecAggregator() {
    // TODO customize
    this.templateCache = CacheBuilder.newBuilder()
            .maximumSize(5000)
            .removalListener(notification -> LOG.debug("Removed {} from template cache for reason {}", notification.getKey(), notification.getCause()))
            .recordStats()
            .build();
    this.packetCache = CacheBuilder.newBuilder()
            .expireAfterWrite(1, TimeUnit.MINUTES)
            .maximumWeight(Size.megabytes(1).toBytes())
            .removalListener((RemovalListener<TemplateKey, Queue<PacketBytes>>) notification -> LOG.debug("Removed {} from packet cache for reason {}", notification.getKey(), notification.getCause()))
            .weigher((key, value) -> value.stream().map(PacketBytes::readableBytes).reduce(0, Integer::sum))
            .recordStats()
            .build();
}
 
Example 4
Source Project: robe   Source File: BasicToken.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Configure method for Token generation configurations and encryptor configure
 *
 * @param configuration confiuration for auth bundle
 */
public static void configure(TokenBasedAuthConfiguration configuration) {
    encryptor.setPoolSize(configuration.getPoolSize());          // This would be a good value for a 4-core system
    if (configuration.getServerPassword().equals("auto")) {
        encryptor.setPassword(UUID.randomUUID().toString());
    } else {
        encryptor.setPassword(configuration.getServerPassword());
    }
    encryptor.setAlgorithm(configuration.getAlgorithm());
    encryptor.initialize();
    BasicToken.defaultMaxAge = configuration.getMaxage();

    //Create cache for permissions.
    cache = CacheBuilder.newBuilder()
            .expireAfterAccess(defaultMaxAge, TimeUnit.SECONDS)
            .expireAfterWrite(defaultMaxAge, TimeUnit.SECONDS)
            .build();

}
 
Example 5
Source Project: big-c   Source File: ResourceLocalizationService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * For each of the requested resources for a container, determines the
 * appropriate {@link LocalResourcesTracker} and forwards a 
 * {@link LocalResourceRequest} to that tracker.
 */
private void handleInitContainerResources(
    ContainerLocalizationRequestEvent rsrcReqs) {
  Container c = rsrcReqs.getContainer();
  // create a loading cache for the file statuses
  LoadingCache<Path,Future<FileStatus>> statCache =
      CacheBuilder.newBuilder().build(FSDownload.createStatusCacheLoader(getConfig()));
  LocalizerContext ctxt = new LocalizerContext(
      c.getUser(), c.getContainerId(), c.getCredentials(), statCache);
  Map<LocalResourceVisibility, Collection<LocalResourceRequest>> rsrcs =
    rsrcReqs.getRequestedResources();
  for (Map.Entry<LocalResourceVisibility, Collection<LocalResourceRequest>> e :
       rsrcs.entrySet()) {
    LocalResourcesTracker tracker =
        getLocalResourcesTracker(e.getKey(), c.getUser(),
            c.getContainerId().getApplicationAttemptId()
                .getApplicationId());
    for (LocalResourceRequest req : e.getValue()) {
      tracker.handle(new ResourceRequestEvent(req, e.getKey(), ctxt));
    }
  }
}
 
Example 6
Source Project: samza   Source File: CachingTableProvider.java    License: Apache License 2.0 6 votes vote down vote up
private ReadWriteTable createDefaultCacheTable(String tableId, JavaTableConfig tableConfig) {
  long readTtlMs = Long.parseLong(tableConfig.getForTable(tableId, CachingTableDescriptor.READ_TTL_MS, "-1"));
  long writeTtlMs = Long.parseLong(tableConfig.getForTable(tableId, CachingTableDescriptor.WRITE_TTL_MS, "-1"));
  long cacheSize = Long.parseLong(tableConfig.getForTable(tableId, CachingTableDescriptor.CACHE_SIZE, "-1"));

  CacheBuilder cacheBuilder = CacheBuilder.newBuilder();
  if (readTtlMs != -1) {
    cacheBuilder.expireAfterAccess(readTtlMs, TimeUnit.MILLISECONDS);
  }
  if (writeTtlMs != -1) {
    cacheBuilder.expireAfterWrite(writeTtlMs, TimeUnit.MILLISECONDS);
  }
  if (cacheSize != -1) {
    cacheBuilder.maximumSize(cacheSize);
  }

  logger.info(String.format("Creating default cache with: readTtl=%d, writeTtl=%d, maxSize=%d",
      readTtlMs, writeTtlMs, cacheSize));

  GuavaCacheTable cacheTable = new GuavaCacheTable(tableId + "-def-cache", cacheBuilder.build());
  cacheTable.init(this.context);

  return cacheTable;
}
 
Example 7
Source Project: airpal   Source File: SchemaCache.java    License: Apache License 2.0 6 votes vote down vote up
public SchemaCache(final QueryRunner.QueryRunnerFactory queryRunnerFactory,
        final ExecutorService executor)
{
    this.queryRunnerFactory = checkNotNull(queryRunnerFactory, "queryRunnerFactory session was null!");
    this.executor = checkNotNull(executor, "executor was null!");

    ListeningExecutorService listeningExecutor = MoreExecutors.listeningDecorator(executor);
    BackgroundCacheLoader<String, Map<String, List<String>>> loader =
            new BackgroundCacheLoader<String, Map<String, List<String>>>(listeningExecutor)
            {
                @Override
                public Map<String, List<String>> load(String catalogName)
                {
                    return queryMetadata(format(
                            "SELECT table_catalog, table_schema, table_name " +
                                    "FROM information_schema.tables " +
                                    "WHERE table_catalog = '%s'",
                            catalogName));
                }
            };

    schemaTableCache = CacheBuilder.newBuilder()
            .refreshAfterWrite(RELOAD_TIME_MINUTES, TimeUnit.MINUTES)
            .build(loader);
}
 
Example 8
Source Project: usergrid   Source File: ApplicationIdCacheImpl.java    License: Apache License 2.0 6 votes vote down vote up
public ApplicationIdCacheImpl(
    final EntityManager managementEnityManager, ManagerCache managerCache, ApplicationIdCacheFig fig) {

    this.managementEnityManager = managementEnityManager;
    this.managerCache = managerCache;

    appCache = CacheBuilder.newBuilder()
        .maximumSize(fig.getCacheSize())
        .expireAfterWrite(fig.getCacheTimeout(), TimeUnit.MILLISECONDS)
        .build(new CacheLoader<String, UUID>() {
            @Override
            public UUID load(final String key) throws Exception {
                UUID appId = fetchApplicationId(key);
                if ( appId == null ) {
                    throw new PersistenceException("Error getting applicationId");
                }
                return appId;
            }
        });
}
 
Example 9
Source Project: buck   Source File: XCConfigurationList.java    License: Apache License 2.0 6 votes vote down vote up
public XCConfigurationList(AbstractPBXObjectFactory objectFactory) {
  buildConfigurations = new ArrayList<>();
  defaultConfigurationName = Optional.empty();
  defaultConfigurationIsVisible = false;

  buildConfigurationsByName =
      CacheBuilder.newBuilder()
          .build(
              new CacheLoader<String, XCBuildConfiguration>() {
                @Override
                public XCBuildConfiguration load(String key) {
                  XCBuildConfiguration configuration =
                      objectFactory.createBuildConfiguration(key);
                  buildConfigurations.add(configuration);
                  return configuration;
                }
              });
}
 
Example 10
public ClusterAgentAutoScaler(TitusRuntime titusRuntime,
                              ClusterOperationsConfiguration configuration,
                              AgentManagementService agentManagementService,
                              V3JobOperations v3JobOperations,
                              SchedulingService<? extends TaskRequest> schedulingService,
                              Scheduler scheduler) {
    this.titusRuntime = titusRuntime;
    this.configuration = configuration;
    this.agentManagementService = agentManagementService;
    this.v3JobOperations = v3JobOperations;
    this.schedulingService = schedulingService;
    this.scheduler = scheduler;
    this.clock = titusRuntime.getClock();
    this.taskIdsForPreviousScaleUps = CacheBuilder.newBuilder()
            .expireAfterWrite(TASK_IDS_PREVIOUSLY_SCALED_TTL_MS, TimeUnit.MILLISECONDS)
            .build();
    this.tierTierAutoScalerExecutions = new HashMap<>();
}
 
Example 11
Source Project: hadoop   Source File: KeyProviderCache.java    License: Apache License 2.0 6 votes vote down vote up
public KeyProviderCache(long expiryMs) {
  cache = CacheBuilder.newBuilder()
      .expireAfterAccess(expiryMs, TimeUnit.MILLISECONDS)
      .removalListener(new RemovalListener<URI, KeyProvider>() {
        @Override
        public void onRemoval(
            RemovalNotification<URI, KeyProvider> notification) {
          try {
            notification.getValue().close();
          } catch (Throwable e) {
            LOG.error(
                "Error closing KeyProvider with uri ["
                    + notification.getKey() + "]", e);
            ;
          }
        }
      })
      .build();
}
 
Example 12
Source Project: kylin-on-parquet-v2   Source File: SnapshotManager.java    License: Apache License 2.0 6 votes vote down vote up
private SnapshotManager(KylinConfig config) {
    this.config = config;
    this.snapshotCache = CacheBuilder.newBuilder().removalListener(new RemovalListener<String, SnapshotTable>() {
        @Override
        public void onRemoval(RemovalNotification<String, SnapshotTable> notification) {
            SnapshotManager.logger.info("Snapshot with resource path {} is removed due to {}",
                    notification.getKey(), notification.getCause());
        }
    }).maximumSize(config.getCachedSnapshotMaxEntrySize())//
            .expireAfterWrite(1, TimeUnit.DAYS).build(new CacheLoader<String, SnapshotTable>() {
                @Override
                public SnapshotTable load(String key) throws Exception {
                    SnapshotTable snapshotTable = SnapshotManager.this.load(key, true);
                    return snapshotTable;
                }
            });
}
 
Example 13
Source Project: skywalking   Source File: ProfileTaskCache.java    License: Apache License 2.0 6 votes vote down vote up
public ProfileTaskCache(ModuleManager moduleManager, CoreModuleConfig moduleConfig) {
    this.moduleManager = moduleManager;

    long initialSize = moduleConfig.getMaxSizeOfProfileTask() / 10L;
    int initialCapacitySize = (int) (initialSize > Integer.MAX_VALUE ? Integer.MAX_VALUE : initialSize);

    profileTaskDownstreamCache = CacheBuilder.newBuilder()
                                             .initialCapacity(initialCapacitySize)
                                             .maximumSize(moduleConfig.getMaxSizeOfProfileTask())
                                             // remove old profile task data
                                             .expireAfterWrite(Duration.ofMinutes(1))
                                             .build();

    profileTaskIdCache = CacheBuilder.newBuilder()
                                     .initialCapacity(initialCapacitySize)
                                     .maximumSize(moduleConfig.getMaxSizeOfProfileTask())
                                     .build();
}
 
Example 14
Source Project: buck   Source File: AppleDependenciesCache.java    License: Apache License 2.0 6 votes vote down vote up
public AppleDependenciesCache(TargetGraph projectGraph) {
  this.depsCache =
      CacheBuilder.newBuilder()
          .build(
              CacheLoader.from(
                  node -> {
                    ImmutableSortedSet.Builder<TargetNode<?>> defaultDepsBuilder =
                        ImmutableSortedSet.naturalOrder();
                    ImmutableSortedSet.Builder<TargetNode<?>> exportedDepsBuilder =
                        ImmutableSortedSet.naturalOrder();
                    AppleBuildRules.addDirectAndExportedDeps(
                        projectGraph,
                        node,
                        defaultDepsBuilder,
                        exportedDepsBuilder,
                        Optional.empty());
                    return new CacheItem(defaultDepsBuilder.build(), exportedDepsBuilder.build());
                  }));
}
 
Example 15
Source Project: act-platform   Source File: ObjectManager.java    License: ISC License 5 votes vote down vote up
private LoadingCache<String, ObjectTypeEntity> createObjectTypeByNameCache() {
  return CacheBuilder.newBuilder()
          .expireAfterAccess(10, TimeUnit.MINUTES)
          .build(new CacheLoader<String, ObjectTypeEntity>() {
            @Override
            public ObjectTypeEntity load(String key) throws Exception {
              return ObjectUtils.notNull(objectTypeDao.get(key), new Exception(String.format("ObjectType with name = %s does not exist.", key)));
            }
          });
}
 
Example 16
Source Project: azure-devops-intellij   Source File: CreatePullRequestModel.java    License: MIT License 5 votes vote down vote up
public CreatePullRequestModel(@NotNull final Project project,
                              @NotNull final GitRepository gitRepository) {
    this.project = project;
    this.gitRepository = gitRepository;

    this.tfGitRemotes = TfGitHelper.getTfGitRemotes(gitRepository);

    this.remoteBranchComboModel = createRemoteBranchDropdownModel();
    this.targetBranch = (GitRemoteBranch) this.remoteBranchComboModel.getSelectedItem();

    this.applicationProvider = new ApplicationProvider();
    this.pullRequestHelper = new PullRequestHelper();

    this.diffCompareInfoProvider = new DiffCompareInfoProvider();
    this.diffCache = CacheBuilder.newBuilder().maximumSize(20)
            .build(
                    new CacheLoader<Pair<String, String>, GitCommitCompareInfo>() {
                        @Override
                        public GitCommitCompareInfo load(Pair<String, String> key) throws Exception {
                            // if we missed the cache, then show the loading spinner, otherwise
                            // just switch to the diff we have to avoid flickering the screen
                            applicationProvider.invokeAndWaitWithAnyModality(new Runnable() {
                                @Override
                                public void run() {
                                    // set the view to show loading
                                    setLoading(true);
                                }
                            });

                            return getDiffCompareInfoProvider()
                                    .getBranchCompareInfo(project, gitRepository, key.getFirst(), key.getSecond());
                        }
                    }
            );

    this.executorService = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
    this.workItems = new HashSet<Integer>();
}
 
Example 17
JSONCodecFactorySupplier() {
    precomputed = CacheBuilder.newBuilder().weakKeys().build(new EagerCacheLoader(this::createFactory));
    shared = CacheBuilder.newBuilder().weakKeys().build(new CacheLoader<SchemaContext, JSONCodecFactory>() {
        @Override
        public JSONCodecFactory load(final SchemaContext key) {
            return createFactory(key, new SharedCodecCache<>());
        }
    });
}
 
Example 18
Source Project: buck   Source File: CoercedTypeCache.java    License: Apache License 2.0 5 votes vote down vote up
CoercedTypeCache(TypeCoercerFactory typeCoercerFactory) {
  this.typeCoercerFactory = typeCoercerFactory;

  constructorArgDescriptorCache =
      CacheBuilder.newBuilder()
          .build(
              new CacheLoader<
                  Class<? extends DataTransferObject>, DataTransferObjectDescriptor<?>>() {
                @Override
                public DataTransferObjectDescriptor<?> load(
                    Class<? extends DataTransferObject> dtoType) {
                  return newConstructorArgDescriptor(dtoType);
                }
              });
}
 
Example 19
Source Project: conductor   Source File: KafkaProducerManager.java    License: Apache License 2.0 5 votes vote down vote up
public KafkaProducerManager(Configuration configuration) {
	this.requestTimeoutConfig = configuration.getProperty(KAFKA_PUBLISH_REQUEST_TIMEOUT_MS, DEFAULT_REQUEST_TIMEOUT);
	this.maxBlockMsConfig = configuration.getProperty(KAFKA_PUBLISH_MAX_BLOCK_MS, DEFAULT_MAX_BLOCK_MS);
	int cacheSize = configuration.getIntProperty(KAFKA_PRODUCER_CACHE_SIZE, DEFAULT_CACHE_SIZE);
	int cacheTimeInMs = configuration.getIntProperty(KAFKA_PRODUCER_CACHE_TIME_IN_MILLIS, DEFAULT_CACHE_TIME_IN_MILLIS);
	this.kafkaProducerCache = CacheBuilder.newBuilder().removalListener(LISTENER)
			.maximumSize(cacheSize).expireAfterAccess(cacheTimeInMs, TimeUnit.MILLISECONDS)
			.build();
}
 
Example 20
public FileCacheGuava(String name, int maxSize) {
  this.name = name;
  this.cache = CacheBuilder.newBuilder().maximumSize(maxSize).recordStats()
      // .removalListener(MY_LISTENER)
      .build(new CacheLoader<String, FileCacheable>() {
        public FileCacheable load(String key) {
          throw new IllegalStateException();
        }
      });
}
 
Example 21
Source Project: DataLink   Source File: AbstractDbDialect.java    License: Apache License 2.0 5 votes vote down vote up
private void initTables(final JdbcTemplate jdbcTemplate) {
    this.tables = CacheBuilder.newBuilder().softValues().build(new CacheLoader<List<String>, Table>() {
        @Override
        public Table load(List<String> names) throws Exception {
            Assert.isTrue(names.size() == 2);
            try {
                beforeFindTable(jdbcTemplate, names.get(0), names.get(0), names.get(1));
                DdlUtilsFilter filter = getDdlUtilsFilter(jdbcTemplate, names.get(0), names.get(0), names.get(1));
                Table table = DdlUtils.findTable(
                        jdbcTemplate,
                        getActualSchemaName(names.get(0)),
                        isGetTablesWithSchema() ? getActualSchemaName(names.get(0)) : null,
                        names.get(1),
                        filter);
                afterFindTable(table, jdbcTemplate, names.get(0), names.get(0), names.get(1));
                if (table == null) {
                    throw new NestableRuntimeException("no found table [" + names.get(0) + "." + names.get(1)
                            + "] , pls check");
                } else {
                    return table;
                }
            } catch (Exception e) {
                throw new NestableRuntimeException("find table [" + names.get(0) + "." + names.get(1) + "] error",
                        e);
            }
        }
    });

}
 
Example 22
Source Project: triplea   Source File: ServerApplication.java    License: GNU General Public License v3.0 5 votes vote down vote up
private static CachingAuthenticator<String, AuthenticatedUser> buildAuthenticator(
    final MetricRegistry metrics, final Jdbi jdbi) {
  return new CachingAuthenticator<>(
      metrics,
      ApiKeyAuthenticator.build(jdbi),
      CacheBuilder.newBuilder().expireAfterAccess(Duration.ofMinutes(10)).maximumSize(10000));
}
 
Example 23
Source Project: albert   Source File: UnitTest.java    License: MIT License 5 votes vote down vote up
public void getNameFromLocalCache() throws Exception{
    //new一个cache的对象出来
    Cache<String/*name*/,String/*nick*/> cache = CacheBuilder.newBuilder().maximumSize(10).build();
    //在get的时候,如果缓存里面没有,则通过实现一个callback的方法去获取
    String name = cache.get("bixiao", new Callable<String>() {
        public String call() throws Exception {
            return "bixiao.zy"+"-"+"iamzhongyong";
        }
    });
    System.out.println(name);
    System.out.println(cache.toString());
}
 
Example 24
Source Project: big-c   Source File: ValueQueue.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Constructor takes the following tunable configuration parameters
 * @param numValues The number of values cached in the Queue for a
 *    particular key.
 * @param lowWatermark The ratio of (number of current entries/numValues)
 *    below which the <code>fillQueueForKey()</code> funciton will be
 *    invoked to fill the Queue.
 * @param expiry Expiry time after which the Key and associated Queue are
 *    evicted from the cache.
 * @param numFillerThreads Number of threads to use for the filler thread
 * @param policy The SyncGenerationPolicy to use when client
 *    calls "getAtMost"
 * @param refiller implementation of the QueueRefiller
 */
public ValueQueue(final int numValues, final float lowWatermark,
    long expiry, int numFillerThreads, SyncGenerationPolicy policy,
    final QueueRefiller<E> refiller) {
  Preconditions.checkArgument(numValues > 0, "\"numValues\" must be > 0");
  Preconditions.checkArgument(((lowWatermark > 0)&&(lowWatermark <= 1)),
      "\"lowWatermark\" must be > 0 and <= 1");
  Preconditions.checkArgument(expiry > 0, "\"expiry\" must be > 0");
  Preconditions.checkArgument(numFillerThreads > 0,
      "\"numFillerThreads\" must be > 0");
  Preconditions.checkNotNull(policy, "\"policy\" must not be null");
  this.refiller = refiller;
  this.policy = policy;
  this.numValues = numValues;
  this.lowWatermark = lowWatermark;
  keyQueues = CacheBuilder.newBuilder()
          .expireAfterAccess(expiry, TimeUnit.MILLISECONDS)
          .build(new CacheLoader<String, LinkedBlockingQueue<E>>() {
                @Override
                public LinkedBlockingQueue<E> load(String keyName)
                    throws Exception {
                  LinkedBlockingQueue<E> keyQueue =
                      new LinkedBlockingQueue<E>();
                  refiller.fillQueueForKey(keyName, keyQueue,
                      (int)(lowWatermark * numValues));
                  return keyQueue;
                }
              });

  executor =
      new ThreadPoolExecutor(numFillerThreads, numFillerThreads, 0L,
          TimeUnit.MILLISECONDS, queue, new ThreadFactoryBuilder()
              .setDaemon(true)
              .setNameFormat(REFILL_THREAD).build());
}
 
Example 25
Source Project: bazel   Source File: PlatformMappingValue.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new mapping value which will match on the given platforms (if a target platform is
 * set on the key to be mapped), otherwise on the set of flags.
 *
 * @param platformsToFlags mapping from target platform label to the command line style flags that
 *     should be parsed & modified if that platform is set
 * @param flagsToPlatforms mapping from a collection of command line style flags to a target
 *     platform that should be set if the flags match the mapped options
 */
PlatformMappingValue(
    Map<Label, Collection<String>> platformsToFlags,
    Map<Collection<String>, Label> flagsToPlatforms) {
  this.platformsToFlags = Preconditions.checkNotNull(platformsToFlags);
  this.flagsToPlatforms = Preconditions.checkNotNull(flagsToPlatforms);
  this.parserCache =
      CacheBuilder.newBuilder()
          .initialCapacity(platformsToFlags.size() + flagsToPlatforms.size())
          .build();
  this.mappingCache = CacheBuilder.newBuilder().weakKeys().build();
}
 
Example 26
/**
 * Constructs a handlebars template engine
 *
 * @param resourceRoot the resource root
 */
public HandlebarsTemplateEngine(String resourceRoot) {
    TemplateLoader templateLoader = new ClassPathTemplateLoader();
    templateLoader.setPrefix(resourceRoot);
    templateLoader.setSuffix(null);

    handlebars = new Handlebars(templateLoader);

    // Set Guava cache.
    Cache<TemplateSource, Template> cache = CacheBuilder.newBuilder().expireAfterWrite(10, TimeUnit.MINUTES)
            .maximumSize(1000).build();

    handlebars = handlebars.with(new GuavaTemplateCache(cache));
}
 
Example 27
@Override
public LoadingCache<String, JSONList> load(final OctaneSharedSpaceAndWorkspaceId sharedSpaceAndWorkspaceId) {
	return CacheBuilder.newBuilder().maximumSize(10)
			.build(new CacheLoader<String, JSONList>() {
				@Override
				public JSONList load(String entityName) {
					return getEntities(sharedSpaceAndWorkspaceId, entityName);
				}
			});
}
 
Example 28
Source Project: joyrpc   Source File: GuavaCacheFactory.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public <K, V> Cache<K, V> build(final String name, final CacheConfig<K, V> config) {
    CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder();
    if (config.getExpireAfterWrite() > 0) {
        cacheBuilder.expireAfterWrite(config.getExpireAfterWrite(), TimeUnit.MILLISECONDS);
    }
    cacheBuilder.maximumSize(config.getCapacity() > 0 ? config.getCapacity() : Long.MAX_VALUE);
    com.google.common.cache.Cache<K, CacheObject<V>> cache = cacheBuilder.build();
    return new GuavaCache<>(cache, config);
}
 
Example 29
Source Project: presto   Source File: RedisJedisManager.java    License: Apache License 2.0 5 votes vote down vote up
@Inject
RedisJedisManager(
        RedisConnectorConfig redisConnectorConfig,
        NodeManager nodeManager)
{
    this.redisConnectorConfig = requireNonNull(redisConnectorConfig, "redisConfig is null");
    this.jedisPoolCache = CacheBuilder.newBuilder().build(CacheLoader.from(this::createConsumer));
    this.jedisPoolConfig = new JedisPoolConfig();
}
 
Example 30
public Cache<String, String> getCache(){
    if (cache == null) {
           cache = CacheBuilder.newBuilder()
                   .initialCapacity(10)
                   .concurrencyLevel(5)
                   .expireAfterWrite(10 * 60, TimeUnit.SECONDS)
                   .build();
       }
       return cache;
}