001/* 002 * Stallion Core: A Modern Web Framework 003 * 004 * Copyright (C) 2015 - 2016 Stallion Software LLC. 005 * 006 * This program is free software: you can redistribute it and/or modify it under the terms of the 007 * GNU General Public License as published by the Free Software Foundation, either version 2 of 008 * the License, or (at your option) any later version. This program is distributed in the hope that 009 * it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of 010 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public 011 * License for more details. You should have received a copy of the GNU General Public License 012 * along with this program. If not, see <http://www.gnu.org/licenses/gpl-2.0.html>. 013 * 014 * 015 * 016 */ 017 018package io.stallion.asyncTasks; 019 020import java.util.concurrent.Executor; 021import java.util.concurrent.ExecutorService; 022import java.util.concurrent.Executors; 023import java.util.concurrent.TimeUnit; 024 025import static io.stallion.utils.Literals.*; 026import static io.stallion.Context.*; 027 028/** 029 * The SimpleAsyncRunner is an alternative way to run asynchronous tasks from AsyncCoordinator. 030 * It is lighter-weight. All it does is accept a Runnable and execute it on a separate thread. 031 * It does not handle failures, exceptions, scheduling, de-duping or anything else. This is 032 * most useful for something like sending an exeception email, where it is more important 033 * to be light-weight than it is important to have fail-safes. 034 * 035 */ 036public class SimpleAsyncRunner { 037 private static SimpleAsyncRunner _instance; 038 private static boolean syncMode = false; 039 040 public static SimpleAsyncRunner instance() { 041 return _instance; 042 } 043 044 public static void load() { 045 _instance = new SimpleAsyncRunner(); 046 } 047 048 public static void setSyncMode(boolean isSyncMode) { 049 syncMode = isSyncMode; 050 } 051 052 public static void shutdown() { 053 if (_instance == null) { 054 return; 055 } 056 _instance.pool.shutdown(); 057 try { 058 _instance.pool.awaitTermination(5, TimeUnit.SECONDS); 059 } catch (InterruptedException e) { 060 061 } 062 _instance = null; 063 } 064 065 private ExecutorService pool; 066 067 public SimpleAsyncRunner() { 068 pool = Executors 069 .newFixedThreadPool(5); 070 } 071 072 public SimpleAsyncRunner submit(Runnable runnable) { 073 if (syncMode) { 074 runnable.run(); 075 } else { 076 pool.submit(runnable); 077 } 078 return this; 079 } 080 081}