java - 什么时候使用异步计算?

标签 java asynchronous nonblocking

我遇到了下面关于异步计算的示例:

//Create an Asynchronous channel. No connection has actually been established yet
 AsynchronousSocketChannel asynchronousSocketChannel = AsynchronousSocketChannel.open(); 

 /**Connect to an actual server on the given port and address. 
    The operation returns a   type of Future, the basis of the all asynchronous operations in java. In this case, a Void is returned because nothing is returned after a successful socket connection
     */
 Void connect = asynchronousSocketChannel.connect(new InetSocketAddress("127.0.0.1", 5000)).get();


 //Allocate data structures to use to communicate over the wire
 ByteBuffer helloBuffer = ByteBuffer.wrap("Hello !".getBytes()); 

 //Send the message

 Future<Integer> successfullyWritten=  asynchronousSocketChannel.write(helloBuffer);

  //Do some stuff here. The point here is that asynchronousSocketChannel.write() returns almost immediately, not waiting to actually finish writing the hello to the channel before returning control to the currently executing thread

 doSomethingElse();

 //now you can come back and check if it was all written (or not)

 System.out.println("Bytes written "+successfullyWritten.get());

我是异步计算新手。但我从您给出的示例中了解到,异步执行操作的全部目的是并行化操作。如果我们同步执行操作,write() 和 doSomethingElse() 就会连续发生。所以选择异步计算的重要属性是:

1) doSomethingElse() 不应依赖于 write() 的输出。

2) write() 和 doSomethingElse() 都应该是耗时的步骤,否则并行化没有意义。对吗?

如果我的理解有误,请纠正我,并且我们通过计算中的异步步骤实现了更多目标。

您还可以介绍一下使用异步计算的最常见用例吗?

最佳答案

是的,基本上您使用异步计算来执行耗时的任务,这些任务应该与其他任务并行运行,例如用户界面线程。不过,“耗时”的含义是一个定义问题,即在某些系统中,它可能意味着“长于几毫秒”。

举个例子,一些“耗时”的任务可能会阻止您的 ui 顶部更新,因此您将异步运行该任务,即与 ui 更新并行(例如,在 Swing 中,这意味着使用工作线程而不是在事件调度线程)。

数据的可用性只是使用异步计算还是同步计算的一个次要指标。您可以推迟任务的执行,直到所需的数据可用(例如通过使用 Future 或消息),同时仍然进行其他计算(例如 ui 更新)。

也就是说,您应该仔细考虑如何对任务进行建模,以减少开销(太多或太小的任务实际上可能会降低性能,不必要地阻塞 CPU 时间等资源)。如果数据的可用性本质上意味着同步计算,那么这可能就是正确的选择。但是,您仍然可以拥有多个异步/并行进程,每个进程同步执行自己的任务。

关于java - 什么时候使用异步计算?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27815847/

相关文章:

java - Spring Mock repository.count() 总是返回 0

angular - RxJS 6 页面不活动时暂停或缓冲可观察

c - Select() 阻塞标准输入,不会超时

mysql - 为什么我收到错误 malloc() : invalid size (unsorted)?

java - JPA将某列的值加一

java - 如何让 WebTestClient 注销所有请求

java - CamelJettyWebSocketServer, fatal error : 42: null cert chain

c# - C#套接字BeginAccept事件停止触发

angular - 等待异步函数返回 Typescript 中的值。

node.js - Node.js 非阻塞行为的新手查询