AbstractUIThreadHandler.java
01 /*
02  * Copyright 2009-2012 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 
17 package org.codehaus.griffon.runtime.util;
18 
19 import griffon.util.GriffonExceptionHandler;
20 import griffon.util.UIThreadHandler;
21 
22 import java.util.concurrent.ExecutorService;
23 import java.util.concurrent.Executors;
24 
25 /**
26  * Base implementation of {@code UIThreadHandler}
27  *
28  @author Andres Almiray
29  */
30 public abstract class AbstractUIThreadHandler implements UIThreadHandler {
31     protected static final ExecutorService DEFAULT_EXECUTOR_SERVICE = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
32     private static final Thread.UncaughtExceptionHandler UNCAUGHT_EXCEPTION_HANDLER = new GriffonExceptionHandler();
33 
34     public void executeOutside(final Runnable runnable) {
35         if (!isUIThread()) {
36             runnable.run();
37         else {
38             DEFAULT_EXECUTOR_SERVICE.submit(new Runnable() {
39                 public void run() {
40                     try {
41                         runnable.run();
42                     catch (Throwable throwable) {
43                         UNCAUGHT_EXCEPTION_HANDLER.uncaughtException(Thread.currentThread(), throwable);
44                     }
45                 }
46             });
47         }
48     }
49 }