private final static <R> R memo(Map<Object, R> cache, List<Object> key, Supplier<R> fn) { synchronized (cache) { R value = cache.get(key); if (value == null) { value = fn.get(); cache.put(key, value); } return value; } } }
public Value<V, R> is(V value, Throwing.Supplier<R> result) { return is(source -> Objects.equals(source, value), v -> result.get()); }
public R orElseThrow(Throwing.Supplier<Throwable> exception) { return toOptional().orElseThrow(() -> Throwing.sneakyThrow(exception.get())); }
/** * Apply the resource and produces an output. * * @param fn Function to apply. * @param <V> Output type. * @return A new try result. */ public <V> Value<V> apply(Throwing.Function<R, V> fn) { return Try.apply(() -> { try (R r1 = this.r.get()) { if (r1 instanceof ProxyCloseable) { return fn.apply((R) ((ProxyCloseable) r1).resource); } return fn.apply(r1); } }); }
/** * Creates a new try from given value provider. * * @param fn Value provider. * @param <V> Value type. * @return A new success try or failure try in case of exception. */ public static <V> Value<V> apply(Throwing.Supplier<? extends V> fn) { try { return new Success<>(fn.get()); } catch (Throwable x) { return new Failure(x); } }
@Override public R tryGet() throws Throwable { if (parent instanceof ProxyCloseable) { ProxyCloseable proxy = (ProxyCloseable) parent; if (proxy.resource == null) { proxy.get(); } this.parentResource = (P) proxy.resource; } else { this.parentResource = parent.get(); } this.resource = mapper.apply(parentResource); return (R) this; } }
/** * Run an operation over the resource. * * @param fn Function to apply. * @return A new try result. */ public Try run(Throwing.Consumer<R> fn) { return Try.run(() -> { try (R r1 = this.r.get()) { fn.accept(r1); } }); } }
public <T extends V> Value<V, R> is(Throwing.Predicate<T> predicate, Throwing.Supplier<R> result) { return is(predicate, v -> result.get()); }
private static <T> T newObject(final Class<T> klass) { return throwingSupplier(klass::newInstance).get(); }
@Override public MemcachedClient get() { client = throwingSupplier(() -> { ConnectionFactory connectionFactory = builder.build(); this.builder = null; return new MemcachedClient(connectionFactory, servers); }).get(); return client; }
private static <R> R fn(Supplier<R> fn, Supplier<R> orElse) { try { return fn.tryGet(); } catch (Throwable x) { if (isFatal(x)) { throw sneakyThrow(x); } return orElse.get(); } }
private static <T> T newObject(final Class<T> klass) { return throwingSupplier(klass::newInstance).get(); }
@Override public MemcachedClient get() { client = throwingSupplier(() -> { ConnectionFactory connectionFactory = builder.build(); this.builder = null; return new MemcachedClient(connectionFactory, servers); }).get(); return client; }