Sobes.tech
Junior — Middle

Describe what the Phaser class is in the context of the monitoring mechanism in programming.

sobes.tech AI

Answer from AI

The Phaser class in Java is a synchronizer that allows coordinating the execution of multiple threads divided into phases. It is similar to CountDownLatch and CyclicBarrier, but more flexible.

Main features:

  • Allows threads to register and deregister dynamically.
  • Supports multiple phases: after all registered threads call arrive(), the phase is considered complete, and the next phase begins.
  • You can override the onAdvance() method to perform actions when transitioning between phases or when the work is finished.

Example of usage:

Phaser phaser = new Phaser(3); // 3 participants

Runnable task = () -> {
    System.out.println(Thread.currentThread().getName() + " started phase 1");
    phaser.arriveAndAwaitAdvance(); // wait for others

    System.out.println(Thread.currentThread().getName() + " started phase 2");
    phaser.arriveAndAwaitAdvance();

    phaser.arriveAndDeregister(); // exit from phaser
};

for (int i = 0; i < 3; i++) {
    new Thread(task).start();
}

Thus, Phaser is used for phased thread synchronization with the ability to dynamically change the number of participants.