private void anotherAsync() { try { final AsyncEntry entry = SphU.asyncEntry("test-another-async"); CompletableFuture.runAsync(() -> { ContextUtil.runOnContext(entry.getAsyncContext(), () -> { try { TimeUnit.SECONDS.sleep(2); // Normal entry nested in asynchronous entry. anotherSyncInAsync(); System.out.println("Async result: 666"); } catch (InterruptedException e) { // Ignore. } finally { entry.exit(); } }); }); } catch (BlockException ex) { ex.printStackTrace(); } }
private void doAsyncThenSync() { try { // First we call an asynchronous resource. final AsyncEntry entry = SphU.asyncEntry("test-async"); this.invoke("abc", resp -> { // The thread is different from original caller thread for async entry. // So we need to wrap in the async context so that nested invocation entry // can be linked to the parent asynchronous entry. ContextUtil.runOnContext(entry.getAsyncContext(), () -> { try { // In the callback, we do another async invocation several times under the async context. for (int i = 0; i < 7; i++) { anotherAsync(); } System.out.println(resp); // Then we do a sync (normal) entry under current async context. fetchSyncInAsync(); } finally { // Exit the async entry. entry.exit(); } }); }); // Then we call a sync resource. fetchSync(); } catch (BlockException ex) { // Request blocked, handle the exception. ex.printStackTrace(); } }