1 16 17 package org.springframework.core.task; 18 19 import java.io.Serializable ; 20 21 import org.springframework.util.Assert; 22 import org.springframework.util.ClassUtils; 23 import org.springframework.util.ConcurrencyThrottleSupport; 24 import org.springframework.util.CustomizableThreadCreator; 25 26 45 public class SimpleAsyncTaskExecutor extends CustomizableThreadCreator implements AsyncTaskExecutor, Serializable { 46 47 52 public static final String DEFAULT_THREAD_NAME_PREFIX = 53 ClassUtils.getShortName(SimpleAsyncTaskExecutor.class) + "-"; 54 55 58 public static final int UNBOUNDED_CONCURRENCY = ConcurrencyThrottleSupport.UNBOUNDED_CONCURRENCY; 59 60 63 public static final int NO_CONCURRENCY = ConcurrencyThrottleSupport.NO_CONCURRENCY; 64 65 66 69 private final ConcurrencyThrottleAdapter concurrencyThrottle = new ConcurrencyThrottleAdapter(); 70 71 72 75 public SimpleAsyncTaskExecutor() { 76 super(); 77 } 78 79 83 public SimpleAsyncTaskExecutor(String threadNamePrefix) { 84 super(threadNamePrefix); 85 } 86 87 88 98 public void setConcurrencyLimit(int concurrencyLimit) { 99 this.concurrencyThrottle.setConcurrencyLimit(concurrencyLimit); 100 } 101 102 105 public int getConcurrencyLimit() { 106 return this.concurrencyThrottle.getConcurrencyLimit(); 107 } 108 109 115 public boolean isThrottleActive() { 116 return this.concurrencyThrottle.isThrottleActive(); 117 } 118 119 120 125 public void execute(Runnable task) { 126 execute(task, TIMEOUT_INDEFINITE); 127 } 128 129 138 public void execute(Runnable task, long startTimeout) { 139 Assert.notNull(task, "Runnable must not be null"); 140 if (isThrottleActive() && startTimeout > TIMEOUT_IMMEDIATE) { 141 this.concurrencyThrottle.beforeAccess(); 142 doExecute(new ConcurrencyThrottlingRunnable(task)); 143 } 144 else { 145 doExecute(task); 146 } 147 } 148 149 156 protected void doExecute(Runnable task) { 157 createThread(task).start(); 158 } 159 160 161 166 private static class ConcurrencyThrottleAdapter extends ConcurrencyThrottleSupport { 167 168 protected void beforeAccess() { 169 super.beforeAccess(); 170 } 171 172 protected void afterAccess() { 173 super.afterAccess(); 174 } 175 } 176 177 178 182 private class ConcurrencyThrottlingRunnable implements Runnable { 183 184 private final Runnable target; 185 186 public ConcurrencyThrottlingRunnable(Runnable target) { 187 this.target = target; 188 } 189 190 public void run() { 191 try { 192 this.target.run(); 193 } 194 finally { 195 concurrencyThrottle.afterAccess(); 196 } 197 } 198 } 199 200 } 201 | Popular Tags |