SuperAPI AI Directory

guava-patterns

General & other

View repository

Updated 10-15 21:48

About this skill

Google Guava best practice patterns

Source: Guava Wiki | GitHub: google/guava

Capability Boundaries

✅ Strong Suits

  1. Immutable collections three patterns — of()Static constants / copyOf()Defensive copying / builder()Incremental building
  2. Cache pattern selection — Cache (no default loading) vs LoadingCache (with default loading function) vs Caffeine (high performance)
  3. Joiner/Splitter pipelines — functional composition, instances are thread-safe and can be used as static final constants
  4. CharMatcher — predefined character class operations, more readable and safer than regex
  5. Preconditions — the checkArgument/checkNotNull/checkState trio, formatted messages (similar to printf)
  6. CaseFormat — conversion between ASCII naming styles such as LOWER_CAMEL/UPPER_UNDERSCORE

❌ Out of Scope

  1. ListenableFuture → has been replaced by Java8 CompletableFuture, do not use it anymore
  2. EventBus → in-process only, for cross-service use kafka-patterns
  3. High-performance cache → caffeine-patterns(API-compatible with Guava, better performance)

Core patterns

Pattern 1: Immutable collections three choices

// ✅ of() — 编译期已知元素(作静态常量)
public static final ImmutableSet<String> COLORS = ImmutableSet.of("red","green","blue");

// ✅ copyOf() — 防御性拷贝(接收外部集合)
class Foo {
    final ImmutableSet<Bar> bars;
    Foo(Set<Bar> bars) { this.bars = ImmutableSet.copyOf(bars); }
}

// ✅ builder() — 渐进构建(合并多来源)
ImmutableSet<Color> colors = ImmutableSet.<Color>builder()
    .addAll(WEBSAFE_COLORS).add(new Color(0,191,255)).build();

// ❌ Collections.unmodifiableXXX — 冗长/不安全(持有引用仍可改)/低效(保留并发检查)

Pattern 2: Cache selection decision

有明确的"未命中→加载"函数 → LoadingCache (get(key)自动加载)
加载函数因key而异 → Cache (get(key, callable)每次指定)
高频+高并发+追求性能 → Caffeine (API兼容,窗口TinyLFU)
多实例共享 → Redis
// ✅ LoadingCache: 统一加载函数
LoadingCache<String, User> cache = CacheBuilder.newBuilder()
    .maximumSize(1000).expireAfterWrite(10, TimeUnit.MINUTES)
    .build(new CacheLoader<>() { public User load(String k) { return loadDB(k); }});
User u = cache.get("user:1");  // 自动加载+缓存

// ✅ 异步刷新(旧值仍可用,后台加载新值)
LoadingCache<String, Config> cfg = CacheBuilder.newBuilder()
    .refreshAfterWrite(1, TimeUnit.MINUTES)
    .build(new CacheLoader<>() { public Config load(String k) { ... }});

// ✅ RemovalListener: 异步拆除资源避免阻塞缓存
RemovalListener<String, Conn> listener = RemovalListeners.asynchronous(
    notif -> notif.getValue().close(), executor);

Pattern 3: Joiner/Splitter immutable pipelines

// Joiner: 实例不可变,可作 static final 常量
private static final Joiner JOINER = Joiner.on(",").skipNulls();
JOINER.join(list);                                    // "a,b,c"
Joiner.on("; ").useForNull("N/A").join("a",null,"c");  // "a; N/A; c"

// Splitter: 链式修饰 trimResults → omitEmptyStrings → limit
List<String> parts = Splitter.on(',').trimResults()
    .omitEmptyStrings().splitToList("foo,bar,,  qux");  // ["foo","bar","qux"]

// Map Splitter: URL参数解析
Map<String,String> m = Splitter.on('&')
    .withKeyValueSeparator('=').split("id=123&name=foo");

// 固定长度切分
Splitter.fixedLength(3).splitToList("abcdefg");  // ["abc","def","g"]

Pattern 4: CharMatcher instead of regex

// ✅ CharMatcher — 编译期类型安全,比正则更可读
CharMatcher.digit().retainFrom("abc123");           // "123"
CharMatcher.javaIsoControl().removeFrom(string);     // 删除控制字符
CharMatcher.whitespace().trimAndCollapseFrom(" foo   bar ", ' '); // "foo bar"
CharMatcher.inRange('a','z').or(CharMatcher.is('_')).matchesAllOf(input);

// ❌ 反模式:Pattern.compile("\\d+") — CharMatcher 更优

Pattern 5: Preconditions vs Objects

// ✅ Guava Preconditions: 格式化消息(类似printf)
checkNotNull(obj, "参数不能为空: %s", userId);
checkArgument(age > 0, "年龄必须>0: %s", age);

// ✅ Java Objects: 简单非空(无格式化)
Objects.requireNonNull(obj, "参数不能为空");
// 选择: 需要消息格式化 → Preconditions; 简单判空 → Objects

Gotchas

  1. ImmutableList.of() does not accept null — throws NPE if it contains null, use Collections.unmodifiableList if null is needed
  2. Cache.get() throws ExecutionException on loading failure — requires try-catch or getUnchecked()
  3. expireAfterAccess vs expireAfterWrite — access is suitable for frequent reads (sessions), write is suitable for stable data
  4. refreshAfterWrite must be less than expireAfterWrite — otherwise the refresh executes after expiration, which is meaningless
  5. Guava Reflect/ListenableFuture have been replaced by the JDK — do not use the Guava versions on Java8+
  6. Caffeine outperforms Guava Cache — prefer Caffeine for new projects, use Guava only for compatibility in old projects
  7. CharMatcher only matches a single character — multi-character patterns (such as keyword matching) still require regex

Data Privacy

This skill does not collect, store, or transmit any user data.