How to do it...

Follow these steps to implement the example:

  1. Create a class named FileSearch and specify that it implements the Runnable interface. This class implements the operation of searching for files with a determined extension modified in the last 24 hours in a folder and its subfolders:
        public class FileSearch implements Runnable {
  1. Declare a private String attribute to store the folder in which the search operation will begin:
        private final String initPath;
  1. Declare another private String attribute to store the extension of the files we are going to look for:
        private final String fileExtension
  1. Declare a private List attribute to store the full path of the files we will find with the desired characteristics:
        private List<String> results;
  1. Finally, declare a private Phaser attribute to control the synchronization of the different phases of the task:
        private Phaser phaser;
  1. Next, implement the constructor of the class that will initialize the attributes of the class. It receives the full path of the initial folder as parameters, the extension of the files, and phaser:
        public FileSearch(String initPath, String fileExtension,
Phaser phaser) {
this.initPath = initPath;
this.fileExtension = fileExtension;
this.phaser=phaser;
results=new ArrayList<>();
}
  1. Now, implement some auxiliary methods that will be used by the run() method. The first one is the directoryProcess() method. It receives a File object as a parameter and it processes all its files and subfolders. For each folder, the method will make a recursive call while passing the folder as a parameter. For each file, the method will call the fileProcess() method:
        private void directoryProcess(File file) { 

File list[] = file.listFiles();
if (list != null) {
for (int i = 0; i < list.length; i++) {
if (list[i].isDirectory()) {
directoryProcess(list[i]);
} else {
fileProcess(list[i]);
}
}
}
}
  1. Then, implement the fileProcess() method. It receives a File object as a parameter and checks whether its extension is equal to the one we are looking for. If they are equal, this method adds the absolute path of the file to the list of results:
        private void fileProcess(File file) { 
if (file.getName().endsWith(fileExtension)) {
results.add(file.getAbsolutePath());
}
}
  1. Now implement the filterResults() method. It doesn't receive any parameter and filters the list of files obtained in the first phase; it deletes files that were modified more than 24 hours ago. First, create a new empty list and get the actual date:
        private void filterResults() { 
List<String> newResults=new ArrayList<>();
long actualDate=new Date().getTime();
  1. Then, go through all the elements of the results list. For each path in the list of results, create a File object for the file and get its last modified date:
        for (int i=0; i<results.size(); i++){ 
File file=new File(results.get(i));
long fileDate=file.lastModified();
  1. Then, compare this date with the actual date, and if the difference is less than 1 day, add the full path of the file to the new list of results:
          if (actualDate-fileDate< TimeUnit.MILLISECONDS
.convert(1,TimeUnit.DAYS)){
newResults.add(results.get(i));
}
}
  1. Finally, change the old results list to the new ones:
          results=newResults; 
}
  1. Next, implement the checkResults() method. This method will be called at the end of the first and second phase, and it will check whether the results list is empty or not. This method doesn't have any parameters:
        private boolean checkResults() {
  1. First, check the size of the results list. If it's 0, the object writes a message to the console indicating this. After this, it calls the arriveAndDeregister() method of the Phaser object to notify that this thread has finished the actual phase and it leaves the phased operation:
        if (results.isEmpty()) { 
System.out.printf("%s: Phase %d: 0 results. ",
Thread.currentThread().getName(),
phaser.getPhase());
System.out.printf("%s: Phase %d: End. ",
Thread.currentThread().getName(),
phaser.getPhase());
phaser.arriveAndDeregister();
return false;
  1. If the results list has elements, the object writes a message to the console indicating this. Then, it calls the arriveAndAwaitAdvance() method of the Phaser object to notify that this thread has finished the actual phase and it wants to be blocked until all the participant threads in the phased operation finish the actual phase:
          } else { 
System.out.printf("%s: Phase %d: %d results. ",
Thread.currentThread().getName(),
phaser.getPhase(),results.size());
phaser.arriveAndAwaitAdvance();
return true;
}
}
  1. The last auxiliary method is the showInfo() method that prints the elements of the results list to the console:
        private void showInfo() { 
for (int i=0; i<results.size(); i++){
File file=new File(results.get(i));
System.out.printf("%s: %s ",
Thread.currentThread().getName(),
file.getAbsolutePath());
}
phaser.arriveAndAwaitAdvance();
}
  1. It's time to implement the run() method that executes the operation using the auxiliary methods described earlier. We'll also implement the Phaser object to control the change between phases. First, call the arriveAndAwaitAdvance() method of the Phaser object. The search won't begin until all the threads have been created:
        @Override 
public void run() {
phaser.arriveAndAwaitAdvance();
  1. Then, write a message to the console indicating the start of the search task:
        System.out.printf("%s: Starting.
",
Thread.currentThread().getName());
  1. Check that the initPath attribute stores the name of a folder and use the directoryProcess() method to find the files with the specified extension in that folder and all its subfolders:
        File file = new File(initPath); 
if (file.isDirectory()) {
directoryProcess(file);
}
  1. Check whether there are any results using the checkResults() method. If there are no results, finish the execution of the thread with the return keyword:
        if (!checkResults()){ 
return;
}
  1. Filter the list of results using the filterResults() method:
        filterResults();
  1. Check whether there are any results using the checkResults() method once again. If there are no results, finish the execution of the thread with the return keyword:
        if (!checkResults()){ 
return;
}
  1. Print the final list of results to the console with the showInfo() method, deregister the thread, and print a message indicating the finalization of the thread:
        showInfo(); 
phaser.arriveAndDeregister();
System.out.printf("%s: Work completed. ",
Thread.currentThread().getName());
  1. Now, implement the main class of the example by creating a class named Main and adding the main() method to it:
        public class Main { 
public static void main(String[] args) {
  1. Create a Phaser object with three participants:
        Phaser phaser=new Phaser(3);
  1. Create three FileSearch objects with a different initial folder for each one. Look for the files with the .log extension:
        FileSearch system=new FileSearch("C:\Windows", "log", phaser); 
FileSearch apps= new FileSearch("C:\Program Files",
"log",phaser);
FileSearch documents= new FileSearch("C:\Documents And Settings",
"log",phaser);
  1. Create and start a thread to execute the first FileSearch object:
        Thread systemThread=new Thread(system,"System"); 
systemThread.start();
  1. Create and start a thread to execute the second FileSearch object:
        Thread appsThread=new Thread(apps,"Apps"); 
appsThread.start();
  1. Create and start a thread to execute the third FileSearch object:
        Thread documentsThread=new Thread(documents, "Documents"); 
documentsThread.start();
  1. Wait for the finalization of the three threads:
        try { 
systemThread.join();
appsThread.join();
documentsThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
  1. Write the value of the finalized flag of the Phaser object using the isFinalized() method:
        System.out.println("Terminated: "+ phaser.isTerminated());
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.108.175