
org.smallibs.concurrent.promise.impl.RunnablePromise Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of hpas Show documentation
Show all versions of hpas Show documentation
Functional ADT And Asynchronous library in Java
/*
* HPAS
* https://github.com/d-plaindoux/hpas
*
* Copyright (c) 2016-2017 Didier Plaindoux
* Licensed under the LGPL2 license.
*/
package org.smallibs.concurrent.promise.impl;
import org.smallibs.data.Maybe;
import org.smallibs.data.Try;
import java.lang.ref.WeakReference;
import java.util.Objects;
import java.util.concurrent.Callable;
import java.util.function.Consumer;
public final class RunnablePromise extends SolvablePromise implements Runnable {
private final Callable callable;
private WeakReference currentExecutor;
public RunnablePromise(Callable callable) {
Objects.requireNonNull(callable);
this.currentExecutor = new WeakReference<>(null);
this.callable = callable;
}
@Override
public void run() {
this.currentExecutor = new WeakReference<>(Thread.currentThread());
try {
solve(Try.success(this.callable.call()));
} catch (final Throwable exception) {
solve(Try.failure(exception));
}
this.currentExecutor.clear();
}
//
// Protected behaviors
//
@Override
protected SolvableFuture createFuture(Consumer> callbackOnComplete) {
return new SolvableFuture(callbackOnComplete) {
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
if (mayInterruptIfRunning) {
Maybe.some(currentExecutor.get()).onSome(Thread::interrupt);
}
return super.cancel(mayInterruptIfRunning);
}
};
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy