| 1 | package org.jtoolkit.essence.concurrency.impl; |
| 2 | |
| 3 | import org.apache.commons.logging.Log; |
| 4 | import org.apache.commons.logging.LogFactory; |
| 5 | import org.jtoolkit.essence.concurrency.Callback; |
| 6 | import org.jtoolkit.essence.concurrency.CallbackEx; |
| 7 | import org.jtoolkit.essence.concurrency.Threads; |
| 8 | import org.jtoolkit.essence.app.Main; |
| 9 | |
| 10 | import java.lang.ref.WeakReference; |
| 11 | import java.util.concurrent.ExecutorService; |
| 12 | |
| 13 | /* |
| 14 | Copyright 2006 Peter Lawrey |
| 15 | |
| 16 | Licensed under the Apache License, Version 2.0 (the "License"); |
| 17 | you may not use this file except in compliance with the License. |
| 18 | You may obtain a copy of the License at |
| 19 | |
| 20 | http://www.apache.org/licenses/LICENSE-2.0 |
| 21 | |
| 22 | Unless required by applicable law or agreed to in writing, software |
| 23 | distributed under the License is distributed on an "AS IS" BASIS, |
| 24 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 25 | See the License for the specific language governing permissions and |
| 26 | limitations under the License. |
| 27 | */ |
| 28 | |
| 29 | /** |
| 30 | * @author Peter Lawrey |
| 31 | */ |
| 32 | @Callback.Threaded |
| 33 | public abstract class ThreadedCallback<T> implements CallbackEx<T> { |
| 34 | protected static final Log LOG = LogFactory.getLog(ThreadedCallback.class); |
| 35 | protected final WeakReference<ExecutorService> executor; |
| 36 | protected final Callback<T> callback; |
| 37 | |
| 38 | protected ThreadedCallback(Callback<T> callback) { |
| 39 | this.callback = callback; |
| 40 | executor = new WeakReference<ExecutorService>(Threads.getCurrentSES()); |
| 41 | } |
| 42 | |
| 43 | protected ExecutorService getExecutorOrFail() { |
| 44 | ExecutorService executor = this.executor.get(); |
| 45 | if (executor == null) |
| 46 | throw new IllegalStateException("Executor no longer running."); |
| 47 | return executor; |
| 48 | } |
| 49 | |
| 50 | protected void handleException(Exception e) { |
| 51 | try { |
| 52 | if (callback instanceof CallbackEx) |
| 53 | ((CallbackEx) callback).onException(e); |
| 54 | else |
| 55 | LOG.error(Main.UNHANDLED_EXCEPTION, e); |
| 56 | } catch (Exception e2) { |
| 57 | LOG.error(Main.UNHANDLED_EXCEPTION, e2); |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | public boolean equals(Object obj) { |
| 62 | if (obj instanceof ThreadedCallback) |
| 63 | return ((ThreadedCallback) obj).callback == callback; |
| 64 | return callback == obj; |
| 65 | } |
| 66 | |
| 67 | public int hashCode() { |
| 68 | return callback.hashCode(); |
| 69 | } |
| 70 | } |