java 异步读写_Java异步与AIO
異步編程提供了一個非阻塞的,事件驅動的編程模型。 這種編程模型利用系統中多核執行任務來提供并行,因此提高了應用的吞吐率。Java異步編程通常需要使用Future,FutureTask和Callable,其中Future代表未來的某個結果,一般是向線程池提交任務時返回。
Future
示例代碼:
public class PromiseTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executor = Executors.newFixedThreadPool(3);
List> futureList = new ArrayList<>();
for (int i = 0; i < 3; i++) {
int finalI = i;
Future future = executor.submit(() -> {
System.out.println("task["+ finalI +"] started!");
Thread.sleep(1000*(3-finalI));// cost some time
System.out.println("task["+ finalI +"]finished!");
return "result["+ finalI +"]";
});
futureList.add(future);
}
for (Future future : futureList) {
System.out.println(future.get());
}
System.out.println("Main thread finished.");
executor.shutdown();
}
}
執行結果:
task[0] started!
task[2] started!
task[1] started!
task[2]finished!
task[1]finished!
task[0]finished!
result[0]
result[1]
result[2]
Main thread finished.
有兩個問題值得注意:
向線程池提交的三個任務同時開始執行,但是在使用get取結果的時候發現必須等耗時最長的任務結束之后才可以得到執行結果。
get方法阻塞了主線程,在取異步任務執行結果期間主線程不可以做其他事情。
這和真正意義上的異步編程模型是違背的,異步編程不存在線程阻塞的情況,因此僅使用Future來完成異步編程是不科學的。
CompletionService
CompletionService提供了一種將生產新的異步任務與使用已完成任務的結果分離開來的服務。生產者 submit 執行的任務,使用者 take 已完成的任務,并按照完成這些任務的順序處理它們的結果,使用者總是可以取到最先完成任務的結果。
public class PromiseTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executor = Executors.newFixedThreadPool(3);
CompletionService service = new ExecutorCompletionService(executor);
for (int i = 0; i < 3; i++) {
int finalI = i;
service.submit(() -> {
System.out.println("task["+ finalI +"] started!");
Thread.sleep(1000*(3-finalI));// cost some time
System.out.println("task["+ finalI +"]finished!");
return "result["+ finalI +"]";
});
}
for (int i = 0; i < 3; i++) {
System.out.println(service.take().get());
}
System.out.println("Main thread finished.");
executor.shutdown();
}
}
執行結果:
task[0] started!
task[2] started!
task[1] started!
task[2]finished!
result[2]
task[1]finished!
result[1]
task[0]finished!
result[0]
Main thread finished.
可見,最耗時的任務在執行時并不影響其他主線程取到已完成任務的結果。但主線程仍然被get方法阻塞。
CompletableFuture
在JDK8發布之前,許多追求性能的框架都自己造了一套異步的實現,例如guava的ListenableFuture和netty的FutureListener,一直到Java8,才有了真正的官方異步實現, CompletableFuture提供了異步操作的支持,使用方法與Js中的Promise類似。
關于CompletableFuture的詳細說明,請參考這篇:Java 8:CompletableFuture終極指南
使用這個API改寫一下代碼:
public class PromiseTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executor = Executors.newFixedThreadPool(3);
for (int i = 0; i < 3; i++) {
int finalI = i;
CompletableFuture future = CompletableFuture.supplyAsync(() -> {
System.out.println("task["+finalI+"] started!");
try {
// time cost
Thread.sleep(1000*(3-finalI));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("task["+finalI+"] finished");
return "result["+finalI+"]";
}, executor);
future.thenAccept(System.out::println);
}
System.out.println("Main thread finished.");
executor.shutdown();
}
}
結果與預期完全一致,各異步任務獨自執行,互相不阻塞。
task[0] started!
Main thread finished.
task[1] started!
task[2] started!
task[2] finished
result[2]
task[1] finished
result[1]
task[0] finished
result[0]
異步IO
從編程模型角度來講,IO操作方式有BIO/NIO/AIO,BIO就是傳統的阻塞IO模型,關于NIO的介紹,也請參考這篇: Java NIO基礎
與NIO區別的是,API提供的讀寫方法均是異步的,即對流或通道內容進行讀寫時并不會阻塞調用的主線程,JDK7在java.nio.channels包新增了以下4個API來支持異步IO:
AsynchronousSocketChannel
AsynchronousServerSocketChannel
AsynchronousFileChannel
AsynchronousDatagramChannel
AIO并沒有加速IO處理速度,只是利用回調和通知機制改變了業務處理時機,使得具體邏輯可以不關注IO結果,只需在合理的時機添加回調即可。
例如:
public class AsyncServer {
public static void main(String[] args) {
try {
AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(8000));
server.accept(null, new CompletionHandler() {
final ByteBuffer buffer = ByteBuffer.allocate(1024);
@Override
public void completed(AsynchronousSocketChannel result, Object attachment) {
Future writeResult = null;
try {
buffer.clear();
result.read(buffer).get(100, TimeUnit.SECONDS);
buffer.flip();
writeResult = result.write(buffer);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
server.accept(null, this);
writeResult.get();
result.close();
} catch (Exception e) {
System.out.println(e.toString());
}
}
}
@Override
public void failed(Throwable exc, Object attachment) {
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}
通過CompletionHandler來添加一些回調,這樣可以很方便地進行異步IO操作。
總結
以上是生活随笔為你收集整理的java 异步读写_Java异步与AIO的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 一加12屏幕惊喜今日揭晓:屏幕中的珠穆朗
- 下一篇: 吉利控股集团与蔚来汽车就换电业务签署合作