import javafx.application.Platform;
import javafx.scene.web.WebView;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

public class Demo2 {

    public static int COUNT = 0;

    public static void main(String[] args) {
        Platform.startup(new Runnable() {
            @Override
            public void run() {
            }
        });
        load();
    }

    private static void load() {
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                doLoad();
            }
        });
    }

    private static void doLoad() {
        final var webView = new WebView();

        webView.getEngine().getLoadWorker().stateProperty().addListener((obs, oldState, newState) -> {
            System.out.println("newState = " + newState);
            if (newState == javafx.concurrent.Worker.State.FAILED) {
                System.out.println("worker has failed");
                System.exit(1);
            }
            if (newState == javafx.concurrent.Worker.State.SUCCEEDED) {
                COUNT++;
                if (COUNT == 100000) {
                    System.out.println("good job you survived!");
                    System.exit(0);
                }
                System.out.println(COUNT);
                CompletableFuture.runAsync(() -> doLoad(), CompletableFuture.delayedExecutor(1, TimeUnit.MILLISECONDS, Platform::runLater))
                        .exceptionally(new Function<Throwable, Void>() {
                            @Override
                            public Void apply(Throwable throwable) {
                                throwable.printStackTrace();
                                System.exit(1);
                                return null;
                            }
                        });
            }
        });
        webView.getEngine().loadContent("hello world");
    }
}