Reputation: 13
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?
Upvotes: 1
Views: 1810
Reputation: 3923
The issue is that the main thread immediately call future.get()
and therefore blocks for the executor to take care of the file read. So in effect you are using 2 threads but only one at a time (for almost all the time).
Some examples on why would you want to use another thread / concurrency:
Remember what I write above are examples that assist in thinking. What you would need to do is to look at your requirements and then design and write the code for concurrency. In this specific case, there is no need for concurrency (due to the immediate future.get()
invocation).
EDIT 1 (based on your comments): If your aim is to understand writing asynchronous tasks then your goal is met with the contrived example that you have listed. However, you can make it more realistic by thinking on the examples that I have provided you or you can think some of your own.
Upvotes: 1