Creates a thread that calls the given code repeatedly, sleeping for an interval of seconds equal to the return value of the previous call. The given afn may be a callable that returns the number of seconds to sleep, or it may be a Callable that returns another Callable that in turn returns the n
(final Callable afn, boolean isDaemon, final Thread.UncaughtExceptionHandler eh,
int priority, final boolean isFactory, boolean startImmediately,
String threadName)
| 384 | * @see Thread |
| 385 | */ |
| 386 | public static SmartThread asyncLoop(final Callable afn, boolean isDaemon, final Thread.UncaughtExceptionHandler eh, |
| 387 | int priority, final boolean isFactory, boolean startImmediately, |
| 388 | String threadName) { |
| 389 | SmartThread thread = new SmartThread(new Runnable() { |
| 390 | @Override |
| 391 | public void run() { |
| 392 | try { |
| 393 | final Callable<Long> fn = isFactory ? (Callable<Long>) afn.call() : afn; |
| 394 | while (true) { |
| 395 | if (Thread.interrupted()) { |
| 396 | throw new InterruptedException(); |
| 397 | } |
| 398 | final Long s = fn.call(); |
| 399 | if (s == null) { // then stop running it |
| 400 | break; |
| 401 | } |
| 402 | if (s > 0) { |
| 403 | Time.sleep(s); |
| 404 | } |
| 405 | } |
| 406 | } catch (Throwable t) { |
| 407 | if (Utils.exceptionCauseIsInstanceOf( |
| 408 | InterruptedException.class, t)) { |
| 409 | LOG.info("Async loop interrupted!"); |
| 410 | return; |
| 411 | } |
| 412 | LOG.error("Async loop died!", t); |
| 413 | throw new RuntimeException(t); |
| 414 | } |
| 415 | } |
| 416 | }); |
| 417 | if (eh != null) { |
| 418 | thread.setUncaughtExceptionHandler(eh); |
| 419 | } else { |
| 420 | thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { |
| 421 | @Override |
| 422 | public void uncaughtException(Thread t, Throwable e) { |
| 423 | LOG.error("Async loop died!", e); |
| 424 | Utils.exitProcess(1, "Async loop died!"); |
| 425 | } |
| 426 | }); |
| 427 | } |
| 428 | thread.setDaemon(isDaemon); |
| 429 | thread.setPriority(priority); |
| 430 | if (threadName != null && !threadName.isEmpty()) { |
| 431 | thread.setName(thread.getName() + "-" + threadName); |
| 432 | } |
| 433 | if (startImmediately) { |
| 434 | thread.start(); |
| 435 | } |
| 436 | return thread; |
| 437 | } |
| 438 | |
| 439 | /** |
| 440 | * Convenience method used when only the function and name suffix are given. |
no test coverage detected