Use Phaser to implement a barrier system and prevent race condition.
*/
package org.jboss.weld.tests.servlet.dispatch;
+import java.util.concurrent.Phaser;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
import jakarta.enterprise.context.ApplicationScoped;
@ApplicationScoped
@@ -23,21 +26,31 @@ public class TestBean {
private int constructions;
private int destructions;
+ private Phaser phaser;
public void constructed() {
constructions++;
+ phaser.register();
}
public void destroyed() {
destructions++;
+ phaser.arriveAndDeregister();
}
public boolean isOk() {
+ try {
+ // either the phaser has already reached stability (phase 0 and terminated) or we wait for it
+ phaser.awaitAdvanceInterruptibly(0, 2l, TimeUnit.SECONDS);
+ } catch (InterruptedException | TimeoutException e) {
+ throw new IllegalStateException("Waiting for Phaser stability failed, exception throws was: " + e);
+ }
return (constructions == destructions) && (constructions + destructions > 0);
}
public void reset() {
constructions = destructions = 0;
+ phaser = new Phaser();
}
public int getConstructions() {
