Async Command API
Valkey GLIDE provides an async command API. All single commands (including MULTI/EXEC, and EVAL) return a asynchronous promise to complete the command wrapped by a CompletableFuture. The CompletableFuture object will return a result when the action is completed, or will throw an Exception if the action times out, is cancelled, or is interrupted. If the command is otherwise unsuccessful, the result will contain an error result and message.
Asynchronous APIs lend themselves well to concurrent calls. See the BenchmarkingApp for an example on how to execute and handle results using an ExecutorService.
ExecutorService executor = new ThreadPoolExecutor( 0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), // include a RejectedExecutionHandler, as some threads may be interrupted (r, poolExecutor) -> { if (!poolExecutor.isShutdown()) { try { poolExecutor.getQueue().put(r); } catch (InterruptedException e) { throw new RuntimeException("interrupted"); } } });The action can be executed in a separate thread by the Executor, for example:
List<CompletableFuture<String>> getCommandTasks = new ArrayList<>();getCommandTasks.add(CompletableFuture.supplyAsync( () -> { try { return client.get("myKey").get(); } catch (Exception e) { throw new RuntimeException(e); } }, executor));
CompletableFuture<String>[] completableAsyncTaskArray = getCommandTasks.toArray(new CompletableFuture[getCommandTasks.size()]);
try { // wait for all futures to complete CompletableFuture.allOf(completableAsyncTaskArray).get();} catch (InterruptedException | ExecutionException e) { e.printStackTrace(); throw new RuntimeException(e);}