Tuesday, September 23, 2008

Finding cyclic calls with state: Google Collections

I found a clever way to detect cyclic calls in Google Collections:

  private static class MemoizingSupplier<T>
      implements SerializableSupplier<T> {
    private final Supplier<T> delegate;
    private MemoizationState state = MemoizationState.NOT_YET;
    private T value;

    public MemoizingSupplier(Supplier<T> delegate) {
      this.delegate = delegate;
    }
    public T get() {
      switch (state) {
        case NOT_YET:
          state = MemoizationState.COMPUTING;
          try {
            value = delegate.get();
          } finally {
            state = MemoizationState.NOT_YET;
          }
          state = MemoizationState.DONE;
          break;
        case COMPUTING:
          throw new CyclicDependencyException();
      }
      return value;
    }
    private static final long serialVersionUID = 1138306392412025275L;
  }

I doubt it is original, but I have not run across this combining of cycle detection with memoizing before. That probably says more about me than Google.

No comments: