01 /*
02 * Copyright 2008-2014 the original author or authors.
03 *
04 * Licensed under the Apache License, Version 2.0 (the "License");
05 * you may not use this file except in compliance with the License.
06 * You may obtain a copy of the License at
07 *
08 * http://www.apache.org/licenses/LICENSE-2.0
09 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.codehaus.griffon.runtime.javafx;
17
18 import griffon.core.GriffonExceptionHandler;
19 import javafx.application.Platform;
20 import org.codehaus.griffon.runtime.core.threading.AbstractUIThreadManager;
21
22 import javax.annotation.Nonnull;
23 import java.util.concurrent.ExecutionException;
24 import java.util.concurrent.FutureTask;
25
26 import static java.util.Objects.requireNonNull;
27
28 /**
29 * @author Dean Iverson
30 */
31 public class JavaFXUIThreadManager extends AbstractUIThreadManager {
32 private static final Thread.UncaughtExceptionHandler UNCAUGHT_EXCEPTION_HANDLER = new GriffonExceptionHandler();
33
34 /**
35 * True if the current thread is the UI thread.
36 */
37 public boolean isUIThread() {
38 return Platform.isFxApplicationThread();
39 }
40
41 @Override
42 public void runInsideUIAsync(@Nonnull Runnable runnable) {
43 requireNonNull(runnable, ERROR_RUNNABLE_NULL);
44 Platform.runLater(runnable);
45 }
46
47 @Override
48 public void runInsideUISync(final @Nonnull Runnable runnable) {
49 requireNonNull(runnable, ERROR_RUNNABLE_NULL);
50 if (isUIThread()) {
51 runnable.run();
52 } else {
53 FutureTask<Void> task = new FutureTask<>(new Runnable() {
54 @Override
55 public void run() {
56 try {
57 runnable.run();
58 } catch (Throwable throwable) {
59 UNCAUGHT_EXCEPTION_HANDLER.uncaughtException(Thread.currentThread(), throwable);
60 }
61 }
62 }, null);
63
64 Platform.runLater(task);
65 try {
66 task.get();
67 } catch (InterruptedException | ExecutionException e) {
68 UNCAUGHT_EXCEPTION_HANDLER.uncaughtException(Thread.currentThread(), e);
69 }
70 }
71 }
72 }
|