Skip to content

Instantly share code, notes, and snippets.

@dcapwell
Created May 17, 2014 22:07
Show Gist options
  • Save dcapwell/1f8fa1d074f473722d61 to your computer and use it in GitHub Desktop.
Save dcapwell/1f8fa1d074f473722d61 to your computer and use it in GitHub Desktop.
Fibers
/**
* Utility class for working with fibers
*/
public final class Fibers {
private Fibers() {
}
/**
* Defines work to run inside a fiber process.
*/
public interface Work<T> {
T apply() throws ExecutionException, InterruptedException, SuspendExecution;
}
/**
* Defines work to run inside a fiber process.
*/
public interface VoidWork {
void apply() throws ExecutionException, InterruptedException, SuspendExecution;
}
public static <T> Fiber<T> of(T t) {
return fiber(null, () -> t);
}
/**
* Creates a new fiber with the given name. The returned fiber will be started.
*/
public static <T> Fiber<T> fiber(final String name, final Work<T> work) {
return new Fiber<T>(name) {
@Override
protected T run() throws SuspendExecution, InterruptedException {
try {
return work.apply();
} catch (ExecutionException e) {
throw Exceptions.rethrow(e);
}
}
}.start();
}
/**
* Creates a new fiber. The returned fiber will be started.
*/
public static <T> Fiber<T> fiber(final Work<T> work) {
return fiber(null, work);
}
/**
* Creates a new fiber with the given name. The returned fiber will be started.
*/
public static Fiber<Void> fiber(final String name, final VoidWork work) {
return fiber(name, () -> {
work.apply();
return null;
});
}
/**
* Creates a new fiber. The returned fiber will be started.
*/
public static Fiber<Void> fiber(final VoidWork work) {
return fiber(null, work);
}
/**
* Sequences the list of fibers into a fiber of list. The order of the returned list matches that of the input.
*/
public static <T> Fiber<List<T>> sequence(final List<Fiber<T>> list) {
return fiber("sequence", () -> {
final List<T> stopwatches = new ArrayList<>(list.size());
for (final Fiber<T> f : list) {
try {
stopwatches.add(f.get());
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
}
return stopwatches;
});
}
public static Work<Stopwatch> time(VoidWork work) {
return () -> {
final Stopwatch stopwatch = Stopwatch.createStarted();
work.apply();
return stopwatch.stop();
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment