Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ReadOnlyBooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;

import javafx.concurrent.Worker;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;

public class Main {
    /**
     * This methods blocks until the worker is done and returns the result value of the worker.
     * If the worker was canceled an exception will be thrown.
     *
     * @param worker The worker
     * @param <T> result type of the worker
     * @return the result
     * @throws InterruptedException if the worker was canceled
     */
    public static <T> T waitFor(Worker<T> worker) throws InterruptedException {
        Lock lock = new ReentrantLock();
        Condition condition = lock.newCondition();
        lock.lock();
        try {
            ReadOnlyBooleanProperty doneProperty = createIsDoneProperty(worker);
            if (doneProperty.get()) {
                return worker.getValue();
            } else {
                doneProperty.addListener(e -> {
                    boolean locked = lock.tryLock();
                    if (locked) {
                        try {
                            condition.signal();
                        } finally {
                            lock.unlock();
                        }
                    } else {
                        throw new RuntimeException("Concurreny Error");
                    }
                });
                condition.await();
                return worker.getValue();
            }
        } finally {
            lock.unlock();
        }
    }

    /**
     * Returns a property that defines the state of the given worker. Once the worker is done the value of the
     * property will be set to true
     * @param worker the worker
     * @return the property
     */
    public static ReadOnlyBooleanProperty createIsDoneProperty(Worker<?> worker) {
        final BooleanProperty property = new SimpleBooleanProperty();
        Consumer<Worker.State> stateChecker = (s) -> {
            if (s.equals(Worker.State.CANCELLED) || s.equals(Worker.State.FAILED)
                    || s.equals(Worker.State.SUCCEEDED)) {
                property.setValue(true);
            } else {
                property.setValue(false);
            }
        };
        worker.stateProperty().addListener((o, oldValue, newValue) -> stateChecker.accept(newValue));
        stateChecker.accept(worker.getState());
        return property;

    }
}