Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (C) 2011 The Guava Authors
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package com.google.common.cache;
 
 import static com.google.common.base.Preconditions.checkArgument;
 
 
 import java.util.List;
 
 import  javax.annotation.Nullable;

A specification of a CacheBuilder configuration.

CacheBuilderSpec supports parsing configuration off of a string, which makes it especially useful for command-line configuration of a CacheBuilder.

The string syntax is a series of comma-separated keys or key-value pairs, each corresponding to a CacheBuilder method.

  • concurrencyLevel=[integer]: sets CacheBuilder.concurrencyLevel.
  • initialCapacity=[integer]: sets CacheBuilder.initialCapacity.
  • maximumSize=[long]: sets CacheBuilder.maximumSize.
  • maximumWeight=[long]: sets CacheBuilder.maximumWeight.
  • expireAfterAccess=[duration]: sets CacheBuilder.expireAfterAccess.
  • expireAfterWrite=[duration]: sets CacheBuilder.expireAfterWrite.
  • refreshAfterWrite=[duration]: sets CacheBuilder.refreshAfterWrite.
  • weakKeys: sets CacheBuilder.weakKeys.
  • softValues: sets CacheBuilder.softValues.
  • weakValues: sets CacheBuilder.weakValues.
  • recordStats: sets CacheBuilder.recordStats.

The set of supported keys will grow as CacheBuilder evolves, but existing keys will never be removed.

Durations are represented by an integer, followed by one of "d", "h", "m", or "s", representing days, hours, minutes, or seconds respectively. (There is currently no syntax to request expiration in milliseconds, microseconds, or nanoseconds.)

Whitespace before and after commas and equal signs is ignored. Keys may not be repeated; it is also illegal to use the following pairs of keys in a single value:

  • maximumSize and maximumWeight
  • softValues and weakValues

CacheBuilderSpec does not support configuring CacheBuilder methods with non-value parameters. These must be configured in code.

A new CacheBuilder can be instantiated from a CacheBuilderSpec using CacheBuilder.from(CacheBuilderSpec) or CacheBuilder.from(String).

Author(s):
Adam Winer
Since:
12.0
 
 public final class CacheBuilderSpec {
  
Parses a single value.
 
   private interface ValueParser {
     void parse(CacheBuilderSpec specString key, @Nullable String value);
   }

  
Splits each key-value pair.
 
   private static final Splitter KEYS_SPLITTER = Splitter.on(',').trimResults();

  
Splits the key from the value.
 
   private static final Splitter KEY_VALUE_SPLITTER = Splitter.on('=').trimResults();

  
Map of names to ValueParser.
 
   private static final ImmutableMap<StringValueParserVALUE_PARSERS =
       ImmutableMap.<StringValueParser>builder()
           .put("initialCapacity"new InitialCapacityParser())
           .put("maximumSize"new MaximumSizeParser())
           .put("maximumWeight"new MaximumWeightParser())
          .put("concurrencyLevel"new ConcurrencyLevelParser())
          .put("weakKeys"new KeyStrengthParser(.))
          .put("softValues"new ValueStrengthParser(.))
          .put("weakValues"new ValueStrengthParser(.))
          .put("recordStats"new RecordStatsParser())
          .put("expireAfterAccess"new AccessDurationParser())
          .put("expireAfterWrite"new WriteDurationParser())
          .put("refreshAfterWrite"new RefreshDurationParser())
          .put("refreshInterval"new RefreshDurationParser())
          .build();
Specification; used for toParseableString().
  private final String specification;
  private CacheBuilderSpec(String specification) {
    this. = specification;
  }

  
Creates a CacheBuilderSpec from a string.

Parameters:
cacheBuilderSpecification the string form
  public static CacheBuilderSpec parse(String cacheBuilderSpecification) {
    CacheBuilderSpec spec = new CacheBuilderSpec(cacheBuilderSpecification);
    if (!cacheBuilderSpecification.isEmpty()) {
      for (String keyValuePair : .split(cacheBuilderSpecification)) {
        List<StringkeyAndValue = ImmutableList.copyOf(.split(keyValuePair));
        checkArgument(!keyAndValue.isEmpty(), "blank key-value pair");
        checkArgument(keyAndValue.size() <= 2,
            "key-value pair %s with more than one equals sign"keyValuePair);
        // Find the ValueParser for the current key.
        String key = keyAndValue.get(0);
        ValueParser valueParser = .get(key);
        checkArgument(valueParser != null"unknown key %s"key);
        String value = keyAndValue.size() == 1 ? null : keyAndValue.get(1);
        valueParser.parse(speckeyvalue);
      }
    }
    return spec;
  }

  
Returns a CacheBuilderSpec that will prevent caching.
  public static CacheBuilderSpec disableCaching() {
    // Maximum size of zero is one way to block caching
    return CacheBuilderSpec.parse("maximumSize=0");
  }

  
Returns a CacheBuilder configured according to this instance's specification.
    CacheBuilder<ObjectObjectbuilder = CacheBuilder.newBuilder();
    if ( != null) {
      builder.initialCapacity();
    }
    if ( != null) {
      builder.maximumSize();
    }
    if ( != null) {
      builder.maximumWeight();
    }
    if ( != null) {
    }
    if ( != null) {
      switch () {
        case :
          builder.weakKeys();
          break;
        default:
          throw new AssertionError();
      }
    }
    if ( != null) {
      switch () {
        case :
          builder.softValues();
          break;
        case :
          builder.weakValues();
          break;
        default:
          throw new AssertionError();
      }
    }
    if ( != null && ) {
      builder.recordStats();
    }
    if ( != null) {
    }
    if ( != null) {
    }
    if ( != null) {
    }
    return builder;
  }

  
Returns a string that can be used to parse an equivalent CacheBuilderSpec. The order and form of this representation is not guaranteed, except that reparsing its output will produce a CacheBuilderSpec equal to this instance.
  public String toParsableString() {
    return ;
  }

  
Returns a string representation for this CacheBuilderSpec instance. The form of this representation is not guaranteed.
  public String toString() {
    return Objects.toStringHelper(this).addValue(toParsableString()).toString();
  }
  public int hashCode() {
    return Objects.hashCode(
        ,
        ,
        ,
        ,
        ,
        ,
        ,
  }
  public boolean equals(@Nullable Object obj) {
    if (this == obj) {
      return true;
    }
    if (!(obj instanceof CacheBuilderSpec)) {
      return false;
    }
    CacheBuilderSpec that = (CacheBuilderSpecobj;
    return Objects.equal(that.initialCapacity)
        && Objects.equal(that.maximumSize)
        && Objects.equal(that.maximumWeight)
        && Objects.equal(that.concurrencyLevel)
        && Objects.equal(that.keyStrength)
        && Objects.equal(that.valueStrength)
        && Objects.equal(that.recordStats)
            durationInNanos(that.writeExpirationDurationthat.writeExpirationTimeUnit))
            durationInNanos(that.accessExpirationDurationthat.accessExpirationTimeUnit))
            durationInNanos(that.refreshDurationthat.refreshTimeUnit));
  }

  
Converts an expiration duration/unit pair into a single Long for hashing and equality. Uses nanos to match CacheBuilder implementation.
  @Nullable private static Long durationInNanos(long duration, @Nullable TimeUnit unit) {
    return (unit == null) ? null : unit.toNanos(duration);
  }

  
Base class for parsing integers.
  abstract static class IntegerParser implements ValueParser {
    protected abstract void parseInteger(CacheBuilderSpec specint value);
    @Override
    public void parse(CacheBuilderSpec specString keyString value) {
      checkArgument(value != null && !value.isEmpty(), "value of key %s omitted"key);
      try {
        parseInteger(spec, Integer.parseInt(value));
      } catch (NumberFormatException e) {
        throw new IllegalArgumentException(
            String.format("key %s value set to %s, must be integer"keyvalue), e);
      }
    }
  }

  
Base class for parsing integers.
  abstract static class LongParser implements ValueParser {
    protected abstract void parseLong(CacheBuilderSpec speclong value);
    @Override
    public void parse(CacheBuilderSpec specString keyString value) {
      checkArgument(value != null && !value.isEmpty(), "value of key %s omitted"key);
      try {
        parseLong(spec, Long.parseLong(value));
      } catch (NumberFormatException e) {
        throw new IllegalArgumentException(
            String.format("key %s value set to %s, must be integer"keyvalue), e);
      }
    }
  }

  
Parse initialCapacity
  static class InitialCapacityParser extends IntegerParser {
    @Override
    protected void parseInteger(CacheBuilderSpec specint value) {
      checkArgument(spec.initialCapacity == null,
          "initial capacity was already set to "spec.initialCapacity);
      spec.initialCapacity = value;
    }
  }

  
Parse maximumSize
  static class MaximumSizeParser extends LongParser {
    @Override
    protected void parseLong(CacheBuilderSpec speclong value) {
      checkArgument(spec.maximumSize == null,
          "maximum size was already set to "spec.maximumSize);
      checkArgument(spec.maximumWeight == null,
          "maximum weight was already set to "spec.maximumWeight);
      spec.maximumSize = value;
    }
  }

  
Parse maximumWeight
  static class MaximumWeightParser extends LongParser {
    @Override
    protected void parseLong(CacheBuilderSpec speclong value) {
      checkArgument(spec.maximumWeight == null,
          "maximum weight was already set to "spec.maximumWeight);
      checkArgument(spec.maximumSize == null,
          "maximum size was already set to "spec.maximumSize);
      spec.maximumWeight = value;
    }
  }

  
Parse concurrencyLevel
  static class ConcurrencyLevelParser extends IntegerParser {
    @Override
    protected void parseInteger(CacheBuilderSpec specint value) {
      checkArgument(spec.concurrencyLevel == null,
          "concurrency level was already set to "spec.concurrencyLevel);
      spec.concurrencyLevel = value;
    }
  }

  
Parse weakKeys
  static class KeyStrengthParser implements ValueParser {
    private final Strength strength;
    public KeyStrengthParser(Strength strength) {
      this. = strength;
    }
    @Override
    public void parse(CacheBuilderSpec specString key, @Nullable String value) {
      checkArgument(value == null"key %s does not take values"key);
      checkArgument(spec.keyStrength == null"%s was already set to %s"keyspec.keyStrength);
      spec.keyStrength = ;
    }
  }

  
Parse weakValues and softValues
  static class ValueStrengthParser implements ValueParser {
    private final Strength strength;
    public ValueStrengthParser(Strength strength) {
      this. = strength;
    }
    @Override
    public void parse(CacheBuilderSpec specString key, @Nullable String value) {
      checkArgument(value == null"key %s does not take values"key);
      checkArgument(spec.valueStrength == null,
        "%s was already set to %s"keyspec.valueStrength);
      spec.valueStrength = ;
    }
  }

  
Parse recordStats
  static class RecordStatsParser implements ValueParser {
    @Override
    public void parse(CacheBuilderSpec specString key, @Nullable String value) {
      checkArgument(value == null"recordStats does not take values");
      checkArgument(spec.recordStats == null"recordStats already set");
      spec.recordStats = true;
    }
  }

  
Base class for parsing times with durations
  abstract static class DurationParser implements ValueParser {
    protected abstract void parseDuration(
        CacheBuilderSpec spec,
        long duration,
        TimeUnit unit);
    @Override
    public void parse(CacheBuilderSpec specString keyString value) {
      checkArgument(value != null && !value.isEmpty(), "value of key %s omitted"key);
      try {
        char lastChar = value.charAt(value.length() - 1);
        TimeUnit timeUnit;
        switch (lastChar) {
          case 'd':
            timeUnit = .;
            break;
          case 'h':
            timeUnit = .;
            break;
          case 'm':
            timeUnit = .;
            break;
          case 's':
            timeUnit = .;
            break;
          default:
            throw new IllegalArgumentException(
                String.format("key %s invalid format.  was %s, must end with one of [dDhHmMsS]",
                    keyvalue));
        }
        long duration = Long.parseLong(value.substring(0, value.length() - 1));
        parseDuration(specdurationtimeUnit);
      } catch (NumberFormatException e) {
        throw new IllegalArgumentException(
            String.format("key %s value set to %s, must be integer"keyvalue));
      }
    }
  }

  
Parse expireAfterAccess
  static class AccessDurationParser extends DurationParser {
    @Override protected void parseDuration(CacheBuilderSpec speclong durationTimeUnit unit) {
      checkArgument(spec.accessExpirationTimeUnit == null"expireAfterAccess already set");
      spec.accessExpirationDuration = duration;
      spec.accessExpirationTimeUnit = unit;
    }
  }

  
Parse expireAfterWrite
  static class WriteDurationParser extends DurationParser {
    @Override protected void parseDuration(CacheBuilderSpec speclong durationTimeUnit unit) {
      checkArgument(spec.writeExpirationTimeUnit == null"expireAfterWrite already set");
      spec.writeExpirationDuration = duration;
      spec.writeExpirationTimeUnit = unit;
    }
  }

  
Parse refreshAfterWrite
  static class RefreshDurationParser extends DurationParser {
    @Override protected void parseDuration(CacheBuilderSpec speclong durationTimeUnit unit) {
      checkArgument(spec.refreshTimeUnit == null"refreshAfterWrite already set");
      spec.refreshDuration = duration;
      spec.refreshTimeUnit = unit;
    }
  }
New to GrepCode? Check out our FAQ X