小编Tha*_*nga的帖子

如何使用Java MongoDriver执行MongoDB js脚本

我使用这个例子在Mongodb服务器中实现了一个JavaScript函数.

当我使用mongo shell时它工作正常,但我想从Java程序内部运行它.这是代码:

public String runFunction() {

    CommandResult commandResult1 = db.command("db.loadServerScripts()");
    CommandResult commandResult2 = db.command("echoFunction(3)");

    return commandResult2.toString();
}
Run Code Online (Sandbox Code Playgroud)

我不明白结果.

java mongodb

6
推荐指数
2
解决办法
1万
查看次数

为什么 CompletableFuture 的 thenAccept() 不在主线程上运行

我在 CompletableFuture 的 SupplyAsync() 中处理长时间运行的操作,并将结果放入 thenAccept() 中。有时 thenAccept() 在主线程上执行,但有时它在工作线程上运行。但我只想在主线程上运行 thenAccept() 操作。这是示例代码。

private void test() {

    ExecutorService executorService = Executors.newSingleThreadExecutor();

    CompletableFuture<String> cf1 = CompletableFuture.supplyAsync(() -> {
        System.out.println("supplyAsync | I am running on : " + Thread.currentThread().getName());
        return "Hello world";
    }, executorService);

    CompletableFuture<Void> cf3 = cf1.thenAccept(s -> {
        System.out.print("thenAccept | I am running on : " + Thread.currentThread().getName());
        System.out.println(" | answer : " + s);
    });

    cf3.thenRun(() -> {
        System.out.println("thenRun | I am running on : " + Thread.currentThread().getName());
        System.out.println();
    });

} …
Run Code Online (Sandbox Code Playgroud)

java completable-future

5
推荐指数
1
解决办法
5182
查看次数

如何在 Java 中实现非阻塞 Futures

Java Future 对象用于获取由并行线程(Executors)执行的异步计算的结果。我们调用 Future.get() 方法并等待结果准备就绪。此示例显示了从 Future 检索结果的非阻塞方式。java-implement-java-non-blocking-futures

NonBlockingExecutor executor = new NonBlockingExecutor(Executors.newSingleThreadExecutor());

NonBlockingFuture<Integer> future = executor.submitNonBlocking(new Callable<Integer>() {

            @Override
            public Integer call() throws Exception {
                String threadName = Thread.currentThread().getName();
                System.out.println(threadName);
                //print -> pool-1-thread-1
                return 1;
            }
});

future.setHandler(new FutureHandler<Integer>() {

       @Override
       public void onSuccess(Integer value) {
            String threadName = Thread.currentThread().getName();
            System.out.println(threadName);
            //print -> pool-1-thread-1
       }

       @Override
       public void onFailure(Throwable e) {
            System.out.println(e.getMessage());
       }
 });

 Thread.sleep(50000);
Run Code Online (Sandbox Code Playgroud)

在此 onSuccess() 方法在并行执行完成后被调用。问题是 onSuccess() 方法没有在主线程上运行。我想在主线程上执行 onSuccess() 方法。我怎样才能解决这个问题。谢谢

java multithreading future nonblocking executorservice

2
推荐指数
2
解决办法
1万
查看次数