Java concurrent synchronization auxiliary class Phaser

Phaser meaning:

more complex and powerful synchronization auxiliary class. It allows concurrent execution of multi-stage tasks. When we have concurrent tasks and need to be decomposed into several steps (CyclicBarrier is divided into two steps), we can choose to use Phaser. The Phaser class mechanism is to synchronize threads at the end of each step, and when all threads have completed this step, the next step is allowed.
Like other synchronization tools, the number of tasks involved in the synchronization operation in the Phaser class must be initialized. The difference is that the number of tasks can be dynamically increased or decreased.

Function:
arriveAndAwaitAdvance(): Similar to the await() method of CyclicBarrier, it waits for the arrival of other threads and continues to execute synchronously.
arriveAndDeregister(): Deregisters the thread that has reached this point from Phaser.
isTerminated(): Determines whether Phaser is terminated.
register(): Register a new participant in Phaser, which will be treated as a thread that has not finished executing this phase.
forceTermination(): Force Phaser to enter the termination state.
... The

example
         uses the Phaser class to synchronize three concurrent tasks. These three tasks will look in three different folders and their subfolders for files that have been modified to a .log extension in the past 24 hours. This task is divided into the following three steps:
1. Obtain files with a .log extension in the executed folder and its subfolders. 2. Filter the results of each step and delete files with
a modification time of more than 24 hours.
The result is printed to the console
At the end of the first step and the second step, it will check whether the found result list has an element. If the result list is empty, the corresponding thread will end execution and be removed from Phaser. (that is, dynamically reducing the number of tasks)

file search class:
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;

public class FileSearch implements Runnable {

    private String initPath;

    private String end;
   
    private List<String> results;

    private Phaser phaser;

    public FileSearch(String initPath, String end, Phaser phaser) {
        this.initPath = initPath; this.end
        = end;
        this.phaser=phaser;
        results=new ArrayList<>();
    }
    @Override
    public void run() {

        phaser.arriveAndAwaitAdvance();//Wait for all threads to be created, make sure that all threads have been created when searching for files
       
        System.out.printf("%s: Starting .\n",Thread.currentThread().getName());
       
        // 1st Phase: find file
        File file = new File(initPath);
        if (file.isDirectory()) {
            directoryProcess(file);
        }
       
        // if If the search result is false, then remove the thread from Phaser and end the running of the thread
        if (!checkResults()){
            return;
        }
       
        // 2nd Phase: Filter the results and filter out those that meet the conditions (within one day). ) result set
        filterResults();
       
        // If the result of the filter result set is empty, then remove the thread from Phaser and prevent it from entering the next stage of execution
        if (!checkResults()){
            return;
        }
       
        // 3rd Phase: 显示结果
        showInfo();
        phaser.arriveAndDeregister();//任务完成,注销掉所有的线程
        System.out.printf("%s: Work completed.\n",Thread.currentThread().getName());
    }
    private void showInfo() {
        for (int i=0; i<results.size(); i++){
            File file=new File(results.get(i));
            System.out.printf("%s: %s\n",Thread.currentThread().getName(),file.getAbsolutePath());
        }
        // Waits for the end of all the FileSearch threads that are registered in the phaser
        phaser.arriveAndAwaitAdvance();
    }
    private boolean checkResults() {
        if (results.isEmpty()) {
            System.out.printf("%s: Phase %d: 0 results.\n",Thread.currentThread().getName(),phaser.getPhase( ));
            System.out.printf("%s: Phase %d: End.\n",Thread.currentThread().getName(),phaser.getPhase());
            //The result is empty, Phaser completes and puts The thread is removed from Phaser
            phaser.arriveAndDeregister();
            return false;
        } else {
            // wait for all threads to find complete
            System.out.printf("%s: Phase %d: %d results.\n",Thread .currentThread().getName(),phaser.getPhase(),results.size());
            phaser.arriveAndAwaitAdvance();
            return true;
        }       
    }
    private void filterResults() {
        List<String> newResults=new ArrayList<>();
        long actualDate=new Date().getTime();
        for (int i=0; i<results.size(); i++){
            File file=new File(results.get(i));
            long fileDate=file.lastModified();
           
            if (actualDate-fileDate<TimeUnit.MILLISECONDS.convert(1,TimeUnit.DAYS)){
                newResults.add(results.get(i));
            }
        }
        results=newResults;
    }
    private void directoryProcess(File file) {
        // Get the content of the directory
        File list[] = file.listFiles();
        if (list != null) {
            for (int i = 0; i < list.length; i++) {
                if (list[i].isDirectory()) {
                    // If is a directory, process it
                    directoryProcess(list[i]);
                } else {
                    // If is a file, process it
                    fileProcess(list[i]);
                }
            }
        }
    }
    private void fileProcess(File file) {
        if (file.getName().endsWith(end)) {
            results.add(file.getAbsolutePath());
        }
    }
}

测试主类:
import java.util.concurrent.Phaser;

public class PhaserMain {

public static void main(String[] args) {

        Phaser phaser = new Phaser(3);

        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);

        Thread systemThread = new Thread(system, "System");
        systemThread.start();
        Thread appsThread = new Thread(apps, "Apps");
        appsThread.start();       
        Thread documentsThread = new Thread(documents, "Documents");
        documentsThread.start();
        try {
            systemThread.join();
            appsThread.join();
            documentsThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.printf("Terminated: %s\n", phaser.isTerminated());
    }

}

海量视频获取


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326161835&siteId=291194637
Recommended