AsynchronousFileChannel and ExecutorService - Java File Path IO

Java examples for File Path IO:File Channel

Description

AsynchronousFileChannel and ExecutorService

Demo Code

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadLocalRandom;

public class Main {
  public static void main(String[] args) {
    final int THREADS = 5;
    ExecutorService taskExecutor = Executors.newFixedThreadPool(THREADS);
    String encoding = System.getProperty("file.encoding");
    List<Future<ByteBuffer>> list = new ArrayList<>();
    int sheeps = 0;
    Path path = Paths.get("C:/folder1/", "test.txt");

    Set<StandardOpenOption> options = new HashSet<>();
    options.add(StandardOpenOption.READ);
    /*from www . j  a  va  2  s. c  o  m*/
    try (AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel
        .open(path, options, taskExecutor)) {
      for (int i = 0; i < 50; i++) {
        Callable<ByteBuffer> worker = new Callable<ByteBuffer>() {
          @Override
          public ByteBuffer call() throws Exception {
            ByteBuffer buffer = ByteBuffer.allocateDirect(ThreadLocalRandom
                .current().nextInt(100, 200));
            asynchronousFileChannel.read(buffer, ThreadLocalRandom.current()
                .nextInt(0, 100));
            return buffer;
          }
        };
        Future<ByteBuffer> future = taskExecutor.submit(worker);
        list.add(future);
      }
      taskExecutor.shutdown();
      while (!taskExecutor.isTerminated()) {
        System.out.println((sheeps += 1));
      }
      for (Future<ByteBuffer> future : list) {
        ByteBuffer buffer = future.get();
        System.out.println("\n\n" + buffer);
        buffer.flip();
        System.out.print(Charset.forName(encoding).decode(buffer));
        buffer.clear();
      }
    } catch (Exception ex) {
      System.err.println(ex);
    }
  }
}

Result


Related Tutorials