Java Concurrency Synchronization helper class Phaser

Source: Internet
Author: User

Phaser meaning:

A more complex and powerful synchronization helper class. It allows concurrent execution of multi-stage tasks. When we have concurrent tasks and need to be broken down into several steps, (Cyclicbarrier is divided into two steps), you can choose to use Phaser. The Phaser class mechanism synchronizes threads at the end of each step, allowing the next step to be performed when all of the threads have completed the process.
As with other synchronization tools, you must initialize the number of tasks in the Phaser class that participate in the synchronization operation, but you can dynamically increase or decrease the number of tasks.

Function:
Arriveandawaitadvance (): Similar to Cyclicbarrier's await () method, which waits for the other threads to arrive after the synchronization continues to execute.
Arriveandderegister (): unregisters the thread executed to this from the phaser.
Isterminated (): Determines whether the phaser terminates.
Register (): Registering a new participant in Phaser, the new participant will be treated as a thread that has not completed this phase.
Forcetermination (): Forces the Phaser to enter the terminating state.
... ...

Example
Use 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 be. Log within the last 24 hours. This task is divided into the following three steps:
1. Get a file with a. log extension in the executing folder and its subfolders
2, filter the results of each step, delete the modified time more than 24 hours of files
3. Print the results to the console
At the end of the first and second steps, you will check that the list of results found is not an element exists. If the result list is empty, the corresponding thread will end execution and be removed from phaser. (i.e. dynamic reduction of the number of tasks)

File Lookup 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<> ();} @Overridepublic void Run () {phaser.arriveandawaitadvance ();//waits for all threads to be created, ensuring that all threads have been created while the file is being searched System.out.prin    TF ("%s:starting.\n", Thread.CurrentThread (). GetName ());    1st Phase: Find Files File = new file (Initpath);    if (File.isdirectory ()) {directoryprocess (file);    }//If the lookup result is false, remove the thread from phaser and end the thread's run if (!checkresults ()) {return;    }//2nd Phase: Filter results, filter out the results set (within one day) filterresults (); If the result of filtering the result set is empty, then remove the thread from the phaser and not let it go to the next stage of execution if (!checkresults()) {return;    }//3rd Phase: Show Results showinfo (); Phaser.arriveandderegister ();//The task is completed, log off all thread 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 is 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 null, phaser completes and removes the thread from the Phaser Phaser.arriveandderegister ();    return false; } else {//waits 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 ()); }}}

To test the main class:

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

Massive video capture Vue Angular

Java Concurrency Synchronization helper class Phaser

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.