Home:ALL Converter>Read a file asynchronously using Future

Read a file asynchronously using Future

Ask Time:2017-05-23T02:47:53         Author:Nexusfactor

Json Formatter

I'm new to threading in general, so bare me with here.

I was reading the following pages about Threading and Executors(1,2). Suppose I wanted to read a large text file asynchronously and return a List collection to iterate though.

According the second link:

The java.util.concurrent.ExecutorService interface represents an asynchronous execution mechanism which is capable of executing tasks in the background.

With this in mind I came up with the following code sample:

The text file (I'm aware the file is too small, let's assume that it had 100+ names):

Sally Solomon
Dick Solomon
Harry Solomon
Tommy Solomon

Code Sample:

String fileName = "C://Users//Nexusfactor//Desktop//read.txt";

ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<List<String>> future = executorService.submit(new Callable<List<String>>(){
    public List<String> call() throws Exception {
        List<String> lstofNames = new ArrayList<String>();
        try (Stream<String> stream = Files.lines(Paths.get(fileName))) 
        {
            lstofNames = stream.collect(Collectors.toList());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return lstofNames;
    }
});
executorService.shutdown();

List<String> display = future.get();

for(String view : display){
    System.out.println(view);
}

Is this the proper way to use a ExecutorService, Future and submit(Callable) to asynchronously read a text file into a list and then iterate though it?

Author:Nexusfactor,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/44120072/read-a-file-asynchronously-using-future
yy