Skip to content

Instantly share code, notes, and snippets.

@NZhuravlev
Last active February 10, 2016 00:02
Show Gist options
  • Save NZhuravlev/4a855c3d0443de25f80e to your computer and use it in GitHub Desktop.
Save NZhuravlev/4a855c3d0443de25f80e to your computer and use it in GitHub Desktop.
package com.doublescoring.socredit.domain;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Event {
private ExecutorService executor = Executors.newCachedThreadPool();
private Runnable errorHandler;
private Runnable successHandler;
private final Object lock = new Object();
private boolean finished;
private boolean failed;
public Event post(String event) {
executor.submit(() -> {
synchronized (lock) {
finished = true;
if (successHandler != null) successHandler.run();
}
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
synchronized (lock) {
failed = true;
if (errorHandler != null) errorHandler.run();
}
}
});
return this;
}
public Event fail(Runnable callback) {
this.errorHandler = callback;
synchronized (lock) {
if (failed) {
this.errorHandler.run();
}
}
return this;
}
public Event done(Runnable callback) {
this.successHandler = callback;
synchronized (lock) {
if (finished) {
this.successHandler.run();
}
}
return this;
}
public static void main(String[] args) {
new Event().post("")
.done(() -> System.out.println("Success!"))
.fail(() -> System.out.println("Fail!!"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment