syndicate-java/src/main/java/org/syndicate_lang/actors/Remote.java

87 lines
2.6 KiB
Java
Raw Normal View History

2020-12-04 18:57:47 +00:00
package org.syndicate_lang.actors;
import java.lang.reflect.Proxy;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
2020-12-04 18:57:47 +00:00
2020-12-04 22:25:40 +00:00
public class Remote<T> {
2020-12-04 18:57:47 +00:00
private final Actor _actor;
private final T _target;
public Remote(Actor actor, T target) {
this._actor = actor;
this._target = target;
}
public Actor getActor() {
return _actor;
}
public void async(BiConsumer<T, Actor> f) {
this._actor.execute(() -> f.accept(this._target, this._actor));
2020-12-04 18:57:47 +00:00
}
public void async(long delayMilliseconds, BiConsumer<T, Actor> f) {
this._actor.later(delayMilliseconds, () -> f.accept(this._target, this._actor));
2020-12-04 18:57:47 +00:00
}
public Promise<?> syncVoid(BiConsumer<T, Actor> f) {
return this.sync((t, ac) -> {
f.accept(t, ac);
2020-12-09 20:04:20 +00:00
return null;
});
2020-12-04 18:57:47 +00:00
}
public Promise<?> syncVoid(long delayMilliseconds, BiConsumer<T, Actor> f) {
return this.sync(delayMilliseconds, (t, ac) -> {
f.accept(t, ac);
2020-12-04 18:57:47 +00:00
return null;
});
}
public<R> Promise<R> sync(BiFunction<T, Actor, R> f) {
2020-12-09 20:04:20 +00:00
Promise<R> p = new Promise<>();
this._actor.execute(
() -> p.resolveWith(f.apply(this._target, this._actor)),
2020-12-09 20:04:20 +00:00
() -> p.rejectWith(this._actor.getExitReason()));
return p;
2020-12-04 18:57:47 +00:00
}
public<R> Promise<R> sync(long delayMilliseconds, BiFunction<T, Actor, R> f) {
2020-12-04 18:57:47 +00:00
Promise<R> p = new Promise<>();
this._actor.later(
delayMilliseconds,
() -> p.resolveWith(f.apply(this._target, this._actor)),
2020-12-04 18:57:47 +00:00
() -> p.rejectWith(this._actor.getExitReason()));
return p;
}
2020-12-04 22:25:40 +00:00
private<I> void checkTargetInstance(Class<I> c) {
2020-12-04 18:57:47 +00:00
if (!c.isInstance(this._target)) {
throw new IllegalArgumentException("target is not an instance of " + c);
}
}
@SuppressWarnings("unchecked")
2020-12-04 22:25:40 +00:00
public<I> I syncProxy(Class<I> c) {
checkTargetInstance(c);
return (I) Proxy.newProxyInstance(c.getClassLoader(), new Class[] { c }, new SyncProxy<>(this));
2020-12-04 18:57:47 +00:00
}
2020-12-04 22:25:40 +00:00
@SuppressWarnings("unchecked")
public<I> I asyncProxy(Class<I> c) {
checkTargetInstance(c);
return (I) Proxy.newProxyInstance(c.getClassLoader(), new Class[] { c }, new AsyncProxy<>(this));
}
@SuppressWarnings("unchecked")
public static<I, T extends I> Remote<T> from(I proxy) {
return ((AbstractProxy<T>) Proxy.getInvocationHandler(proxy)).ref();
2020-12-04 18:57:47 +00:00
}
@Override
public String toString() {
2020-12-04 22:25:40 +00:00
return this.getClass().getSimpleName() + "(" + this._actor.getName() + "::" + this._target + ")";
2020-12-04 18:57:47 +00:00
}
}