Skip to content

Instantly share code, notes, and snippets.

@achim
Last active August 29, 2015 14:07
Show Gist options
  • Save achim/21bf5611ecebaeff5718 to your computer and use it in GitHub Desktop.
Save achim/21bf5611ecebaeff5718 to your computer and use it in GitHub Desktop.
package util;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import javax.annotation.Nullable;
import java.util.concurrent.*;
public class Memoize {
public static <S, T> Function<S, T> memoize(final Function<S, T> func) {
final ConcurrentHashMap<S, Future<T>> futures = new ConcurrentHashMap<>();
return new Function<S, T>() {
@Nullable
@Override
public T apply(@Nullable final S s) {
FutureTask<T> newFuture = new FutureTask<>(new Callable<T>() {
@Override
public T call() throws Exception {
return func.apply(s);
}
});
Future<T> future = Optional.fromNullable(futures.putIfAbsent(s, newFuture)).or(newFuture);
try {
return future.get();
} catch (InterruptedException|ExecutionException e) {
throw new RuntimeException(e);
}
}
};
}
public static <S, T> Function<S, Callable<T>> memoize2(final Function<S, T> func) {
final ConcurrentHashMap<S, Future<T>> futures = new ConcurrentHashMap<>();
return new Function<S, Callable<T>>() {
@Nullable
@Override
public Callable<T> apply(@Nullable final S s) {
FutureTask<T> newFuture = new FutureTask<>(new Callable<T>() {
@Override
public T call() throws Exception {
return func.apply(s);
}
});
final Future<T> future = Optional.fromNullable(futures.putIfAbsent(s, newFuture)).or(newFuture);
return new Callable<T>() {
@Override
public T call() throws Exception {
return future.get();
}
};
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment