Skip to content

Instantly share code, notes, and snippets.

@Tetraquark
Last active July 9, 2019 09:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tetraquark/982132d9231f4c5654737f8c81f6e8ea to your computer and use it in GitHub Desktop.
Save Tetraquark/982132d9231f4c5654737f8c81f6e8ea to your computer and use it in GitHub Desktop.
import org.jetbrains.annotations.NotNull;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SomeJavaApi {
private static final String SUCCESS_RESULT = "SUCCESSFUL_CALL";
private static final long WORK_DELAY = 1000L;
private ExecutorService executorService;
public SomeJavaApi() {
executorService = Executors.newSingleThreadExecutor();
}
public void successRemoteCall(CustomCallback callback) {
System.out.println("[Thread id: " + Thread.currentThread().getId() + "]\t" +
"Start api function with successful result.");
runTask(() -> callback.onSuccess(SUCCESS_RESULT), WORK_DELAY);
}
public void failedRemoteCall(CustomCallback callback) {
System.out.println("[Thread id: " + Thread.currentThread().getId() + "]\t" +
"Start api function with unsuccessful result.");
runTask(() -> callback.onFailure(new Exception("Dangerous exception!")), WORK_DELAY);
}
public void destroy() {
executorService.shutdown();
}
public interface CustomCallback {
void onSuccess(@NotNull String data);
void onFailure(@NotNull Exception exception);
}
private void runTask(Runnable task, long delay) {
executorService.submit(() -> {
try {
if(delay > 0) {
Thread.sleep(delay);
}
task.run();
} catch (Throwable e) {
e.printStackTrace();
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment