| 1 | package org.jtoolkit.essence.concurrency.impl; |
| 2 | |
| 3 | import org.jetbrains.annotations.NotNull; |
| 4 | import org.jetbrains.annotations.Nullable; |
| 5 | import org.jtoolkit.essence.concurrency.Callback; |
| 6 | import org.jtoolkit.essence.concurrency.CallbackEx; |
| 7 | import org.jtoolkit.essence.app.Main; |
| 8 | |
| 9 | import java.util.concurrent.Callable; |
| 10 | |
| 11 | /* |
| 12 | Copyright 2006 Peter Lawrey |
| 13 | |
| 14 | Licensed under the Apache License, Version 2.0 (the "License"); |
| 15 | you may not use this file except in compliance with the License. |
| 16 | You may obtain a copy of the License at |
| 17 | |
| 18 | http://www.apache.org/licenses/LICENSE-2.0 |
| 19 | |
| 20 | Unless required by applicable law or agreed to in writing, software |
| 21 | distributed under the License is distributed on an "AS IS" BASIS, |
| 22 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 23 | See the License for the specific language governing permissions and |
| 24 | limitations under the License. |
| 25 | */ |
| 26 | |
| 27 | /** |
| 28 | * @author Peter Lawrey |
| 29 | */ |
| 30 | |
| 31 | public class ThreadedCallbackImpl<T> extends ThreadedCallback<T> { |
| 32 | public ThreadedCallbackImpl(Callback<T> callback) { |
| 33 | super(callback); |
| 34 | } |
| 35 | |
| 36 | public void onCallback(@NotNull final T value) throws IllegalStateException { |
| 37 | getExecutorOrFail().submit(new Callable<Void>() { |
| 38 | @Nullable public Void call() { |
| 39 | try { |
| 40 | callback.onCallback(value); |
| 41 | } catch (Exception e) { |
| 42 | handleException(e); |
| 43 | } |
| 44 | return null; |
| 45 | } |
| 46 | }); |
| 47 | } |
| 48 | |
| 49 | public void onException(@NotNull final Throwable t) throws IllegalStateException { |
| 50 | if (callback instanceof CallbackEx) |
| 51 | getExecutorOrFail().execute(new Runnable() { |
| 52 | public void run() { |
| 53 | ((CallbackEx) callback).onException(t); |
| 54 | } |
| 55 | }); |
| 56 | else |
| 57 | LOG.warn(Thread.currentThread().getName() + ": " + Main.UNHANDLED_EXCEPTION, t); |
| 58 | } |
| 59 | |
| 60 | public String toString() { |
| 61 | return "TCI exec " + executor.get() + " callback " + callback; |
| 62 | } |
| 63 | } |