Java Code Examples for com.google.common.base.Suppliers#memoize()

The following examples show how to use com.google.common.base.Suppliers#memoize() . 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 File: MarkRemovableRulesetNodes.java    From closure-stylesheets with Apache License 2.0 6 votes vote down vote up
/**
 * Computes whether the given rule is overridden by another rule with some
 * related shorthand property of equal or higher importance.
 *
 * @param propertyNode the property node of the rule to check
 * @param selector the printed representation of the selector of the rule
 * @param rules rulesets occurring after the ruleset to check (represented as
 *     a map from selector/property pairs to rulesets for easy searching)
 * @param ruleset the ruleset to check (assumed to contain one rule)
 * @return whether the given ruleset has an overriding ruleset which uses a
 *     related shorthand property
 */
private boolean hasOverridingShorthand(
    CssPropertyNode propertyNode,
    String selector,
    Table<String, String, CssRulesetNode> rules,
    final CssRulesetNode ruleset) {

  Supplier<Boolean> rulesetIsImportant = Suppliers.memoize(
      new Supplier<Boolean>() {
        @Override
        public Boolean get() {
          return isImportantRule(ruleset);
        }
      });

  for (String shorthand : propertyNode.getProperty().getShorthands()) {
    CssRulesetNode shorthandRuleset = rules.get(selector, shorthand);
    if ((shorthandRuleset != null)
        && (!rulesetIsImportant.get() || isImportantRule(shorthandRuleset))) {
      return true;
    }
  }

  return false;
}
 
Example 2
Source File: AstyanaxTableDAO.java    From emodb with Apache License 2.0 6 votes vote down vote up
private AstyanaxStorage newAstyanaxStorage(long uuid, int shardsLog2, boolean readsAllowed, final String placement,
                                           final String table) {
    // Delay resolving the placement until it's used so we can manipulate table metadata for placements that
    // don't replicate to the current data center.
    return new AstyanaxStorage(uuid, shardsLog2, readsAllowed, placement, Suppliers.memoize(new Supplier<Placement>() {
        @Override
        public Placement get() {
            try {
                return _placementCache.get(placement);
            } catch (UnknownPlacementException e) {
                // Add table information to the exception
                e.setTable(table);
                throw e;
            }
        }
    }));
}
 
Example 3
Source File: ResourceTaskProvidersExtensionPoint.java    From workspacemechanic with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Return the {@link IResourceTaskProvider} supplier, initializing it if required.
 *
 * <p>The supplier is memoized, so it will return the same instantiated
 * objects upon repeated calls.
 */
public static Supplier<List<IResourceTaskProvider>> getInstance() {
  return Suppliers.memoize(new Supplier<List<IResourceTaskProvider>>() {
    public List<IResourceTaskProvider> get() {
      return SingletonHolder.instance.getInstances();
    }
  });
}
 
Example 4
Source File: Rule.java    From joshua with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor used by PackedGrammar's sortRules()
 * @param lhs todo
 * @param sourceRhs todo
 * @param targetRhs todo
 * @param features todo
 * @param arity todo
 * @param owner todo
 */
public Rule(int lhs, int[] sourceRhs, int[] targetRhs, FeatureVector features, int arity, OwnerId owner) {
  this.lhs = lhs;
  this.source = sourceRhs;
  this.arity = arity;
  this.owner = owner;
  this.target = targetRhs;
  this.featuresSupplier = Suppliers.memoize(() -> features);
  this.sparseFeatureStringSupplier = initializeSparseFeaturesStringSupplier();
  this.alignmentSupplier = initializeAlignmentSupplier();
}
 
Example 5
Source File: DepositStorage.java    From teku with Apache License 2.0 5 votes vote down vote up
private DepositStorage(
    final Eth1EventsChannel eth1EventsChannel,
    final Database database,
    final boolean eth1DepositsFromStorageEnabled) {
  this.eth1EventsChannel = eth1EventsChannel;
  this.database = database;
  this.replayResult = Suppliers.memoize(() -> SafeFuture.of(this::replayDeposits));
  this.eth1DepositsFromStorageEnabled = eth1DepositsFromStorageEnabled;
}
 
Example 6
Source File: CommunityList.java    From batfish with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs a CommunityList with the given name for {@link #_name}, and lines for {@link
 * #_lines}
 *
 * @param name The name of the structure
 * @param lines The lines in the list
 */
public CommunityList(
    @Nonnull String name, @Nonnull List<CommunityListLine> lines, boolean invertMatch) {
  _name = name;
  _lines = lines;
  _invertMatch = invertMatch;
  _communityCache = Suppliers.memoize(new CommunityCacheSupplier());
}
 
Example 7
Source File: ProfilerLatticeStatisticProvider.java    From Quicksql with MIT License 5 votes vote down vote up
/** Creates a ProfilerLatticeStatisticProvider. */
private ProfilerLatticeStatisticProvider(Lattice lattice) {
  Objects.requireNonNull(lattice);
  this.profile = Suppliers.memoize(() -> {
    final ProfilerImpl profiler =
        ProfilerImpl.builder()
            .withPassSize(200)
            .withMinimumSurprise(0.3D)
            .build();
    final List<Profiler.Column> columns = new ArrayList<>();
    for (Lattice.Column column : lattice.columns) {
      columns.add(new Profiler.Column(column.ordinal, column.alias));
    }
    final String sql =
        lattice.sql(ImmutableBitSet.range(lattice.columns.size()),
            false, ImmutableList.of());
    final Table table =
        new MaterializationService.DefaultTableFactory()
            .createTable(lattice.rootSchema, sql, ImmutableList.of());
    final ImmutableList<ImmutableBitSet> initialGroups =
        ImmutableList.of();
    final Enumerable<List<Comparable>> rows =
        ((ScannableTable) table).scan(null)
            .select(values -> {
              for (int i = 0; i < values.length; i++) {
                if (values[i] == null) {
                  values[i] = NullSentinel.INSTANCE;
                }
              }
              //noinspection unchecked
              return (List<Comparable>) (List) Arrays.asList(values);
            });
    return profiler.profile(rows, columns, initialGroups);
  })::get;
}
 
Example 8
Source File: BigQueryCredentialsSupplier.java    From presto with Apache License 2.0 5 votes vote down vote up
public BigQueryCredentialsSupplier(Optional<String> credentialsKey, Optional<String> credentialsFile)
{
    requireNonNull(credentialsKey, "credentialsKey is null");
    requireNonNull(credentialsFile, "credentialsFile is null");
    // lazy creation, cache once it's created
    this.credentialsCreator = Suppliers.memoize(() -> {
        Optional<Credentials> credentialsFromKey = credentialsKey.map(BigQueryCredentialsSupplier::createCredentialsFromKey);
        Optional<Credentials> credentialsFromFile = credentialsFile.map(BigQueryCredentialsSupplier::createCredentialsFromFile);
        return Stream.of(credentialsFromKey, credentialsFromFile)
                .flatMap(Streams::stream)
                .findFirst();
    });
}
 
Example 9
Source File: PackedGrammar.java    From joshua with Apache License 2.0 5 votes vote down vote up
private Supplier<byte[]> initializeAlignmentSupplier(){
  return Suppliers.memoize(() ->{
    byte[] raw_alignment = getAlignmentArray(source[address + 2]);
    byte[] points = new byte[raw_alignment.length + 2];
    points[0] = points[1] = 0;
    for (int i = 0; i < raw_alignment.length; i++)
      points[i + 2] = (byte) (raw_alignment[i] + 1);
    return points;
  });
}
 
Example 10
Source File: PickingSlotViewRepository.java    From metasfresh-webui-api-legacy with GNU General Public License v3.0 5 votes vote down vote up
private static Supplier<LookupDataSource> createBPartnerLocationLookup()
{
	return Suppliers.memoize(() -> LookupDataSourceFactory.instance
			.getLookupDataSource(SqlLookupDescriptor.builder()
					.setCtxTableName(null)
					.setCtxColumnName(I_M_PickingSlot.COLUMNNAME_C_BPartner_Location_ID)
					.setDisplayType(DisplayType.Search)
					.setWidgetType(DocumentFieldWidgetType.Lookup)
					.buildForDefaultScope()));
}
 
Example 11
Source File: AndroidBinary.java    From buck with Apache License 2.0 5 votes vote down vote up
private static Supplier<ImmutableSet<JavaLibrary>> createTransitiveClasspathDepsSupplier(
    SourcePathRuleFinder ruleFinder, AndroidGraphEnhancementResult enhancementResult) {
  return Suppliers.memoize(
      () ->
          JavaLibraryClasspathProvider.getClasspathDeps(
              ruleFinder
                  .filterBuildRuleInputs(enhancementResult.getClasspathEntriesToDex().stream())
                  .collect(ImmutableSet.toImmutableSet())));
}
 
Example 12
Source File: RocksDBPlugin.java    From besu with Apache License 2.0 5 votes vote down vote up
private void createAndRegister(final StorageService service) {
  final List<SegmentIdentifier> segments = service.getAllSegmentIdentifiers();

  final Supplier<RocksDBFactoryConfiguration> configuration =
      Suppliers.memoize(options::toDomainObject);
  factory =
      new RocksDBKeyValueStorageFactory(
          configuration, segments, RocksDBMetricsFactory.PUBLIC_ROCKS_DB_METRICS);
  privacyFactory = new RocksDBKeyValuePrivacyStorageFactory(factory);

  service.registerKeyValueStorage(factory);
  service.registerKeyValueStorage(privacyFactory);
}
 
Example 13
Source File: NaturalSplineCurveInterpolator.java    From Strata with Apache License 2.0 5 votes vote down vote up
Bound(DoubleArray xValues, DoubleArray yValues) {
  super(xValues, yValues);
  this.xValues = xValues.toArrayUnsafe();
  this.yValues = yValues.toArrayUnsafe();
  PiecewisePolynomialInterpolator underlying = new NaturalSplineInterpolator();
  this.poly = underlying.interpolate(xValues.toArray(), yValues.toArray());
  this.polySens = Suppliers.memoize(() -> underlying.interpolateWithSensitivity(xValues.toArray(), yValues.toArray()));
}
 
Example 14
Source File: AccessTarget.java    From ArchUnit with Apache License 2.0 4 votes vote down vote up
FieldAccessTarget(FieldAccessTargetBuilder builder) {
    super(builder.getOwner(), builder.getName(), builder.getFullName());
    this.type = builder.getType();
    this.field = Suppliers.memoize(builder.getField());
}
 
Example 15
Source File: ExtensionPointMap.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
Supplier<ExtensionPointInterface> createLazyLoader( PluginInterface extensionPointPlugin ) {
  return Suppliers.memoize( new ExtensionPointLoader( extensionPointPlugin ) );
}
 
Example 16
Source File: MemoizedSupplier.java    From james-project with Apache License 2.0 4 votes vote down vote up
public MemoizedSupplier(Supplier<T> originalSupplier) {
    this.memorizeSupplier = Suppliers.memoize(originalSupplier::get);
    this.valueReference = new AtomicReference<>();
}
 
Example 17
Source File: CollaborationWikiStore.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
public CollaborationWikiStore(final LegacyKVStoreProvider storeProvider) {
  Preconditions.checkNotNull(storeProvider, "kvStore provider required");
  wikiStore = Suppliers.memoize(() -> storeProvider.getStore(CollaborationWikiStore.CollaborationWikiStoreStoreCreator.class));
}
 
Example 18
Source File: JavaField.java    From ArchUnit with Apache License 2.0 4 votes vote down vote up
JavaField(DomainBuilders.JavaFieldBuilder builder) {
    super(builder);
    type = builder.getType();
    fieldSupplier = Suppliers.memoize(new ReflectFieldSupplier());
}
 
Example 19
Source File: PlatformConfig.java    From powsybl-core with Mozilla Public License 2.0 4 votes vote down vote up
protected PlatformConfig(Supplier<ModuleConfigRepository> repositorySupplier, Path configDir) {
    this.repositorySupplier = Suppliers.memoize(Objects.requireNonNull(repositorySupplier));
    this.configDir = FileUtil.createDirectory(configDir);
}
 
Example 20
Source File: JavaMethod.java    From ArchUnit with Apache License 2.0 4 votes vote down vote up
JavaMethod(DomainBuilders.JavaMethodBuilder builder) {
    super(builder);
    throwsClause = builder.getThrowsClause(this);
    methodSupplier = Suppliers.memoize(new ReflectMethodSupplier());
    annotationDefaultValue = builder.getAnnotationDefaultValue();
}