Last active
July 9, 2019 09:37
-
-
Save Tetraquark/982132d9231f4c5654737f8c81f6e8ea to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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