KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > springframework > scheduling > backportconcurrent > ScheduledExecutorFactoryBean


1 /*
2  * Copyright 2002-2007 the original author or authors.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package org.springframework.scheduling.backportconcurrent;
18
19 import edu.emory.mathcs.backport.java.util.concurrent.Executors;
20 import edu.emory.mathcs.backport.java.util.concurrent.RejectedExecutionHandler;
21 import edu.emory.mathcs.backport.java.util.concurrent.ScheduledExecutorService;
22 import edu.emory.mathcs.backport.java.util.concurrent.ScheduledThreadPoolExecutor;
23 import edu.emory.mathcs.backport.java.util.concurrent.ThreadFactory;
24 import edu.emory.mathcs.backport.java.util.concurrent.ThreadPoolExecutor;
25 import org.apache.commons.logging.Log;
26 import org.apache.commons.logging.LogFactory;
27
28 import org.springframework.beans.factory.DisposableBean;
29 import org.springframework.beans.factory.FactoryBean;
30 import org.springframework.beans.factory.InitializingBean;
31 import org.springframework.util.Assert;
32 import org.springframework.util.ObjectUtils;
33
34 /**
35  * {@link org.springframework.beans.factory.FactoryBean} that sets up
36  * a JSR-166 backport
37  * {@link edu.emory.mathcs.backport.java.util.concurrent.ScheduledExecutorService}
38  * (by default:
39  * {@link edu.emory.mathcs.backport.java.util.concurrent.ScheduledThreadPoolExecutor}
40  * as implementation) and exposes it for bean references.
41  *
42  * <p>Allows for registration of {@link ScheduledExecutorTask ScheduledExecutorTasks},
43  * automatically starting the {@link ScheduledExecutorService} on initialization and
44  * cancelling it on destruction of the context. In scenarios that just require static
45  * registration of tasks at startup, there is no need to access the
46  * {@link ScheduledExecutorService} instance itself in application code.
47  *
48  * <p>Note that
49  * {@link edu.emory.mathcs.backport.java.util.concurrent.ScheduledExecutorService}
50  * uses a {@link Runnable} instance that is shared between repeated executions,
51  * in contrast to Quartz which instantiates a new Job for each execution.
52  *
53  * <p>This class is analogous to the
54  * {@link org.springframework.scheduling.timer.TimerFactoryBean}
55  * class for the JDK 1.3 {@link java.util.Timer} facility.
56  *
57  * @author Juergen Hoeller
58  * @since 2.0.3
59  * @see ScheduledExecutorTask
60  * @see edu.emory.mathcs.backport.java.util.concurrent.ScheduledExecutorService
61  * @see edu.emory.mathcs.backport.java.util.concurrent.ScheduledThreadPoolExecutor
62  * @see org.springframework.scheduling.timer.TimerFactoryBean
63  */

64 public class ScheduledExecutorFactoryBean implements FactoryBean, InitializingBean, DisposableBean {
65
66     protected final Log logger = LogFactory.getLog(getClass());
67
68     private ScheduledExecutorTask[] scheduledExecutorTasks;
69
70     private int poolSize = 1;
71
72     private ThreadFactory threadFactory = Executors.defaultThreadFactory();
73
74     private RejectedExecutionHandler rejectedExecutionHandler = new ThreadPoolExecutor.AbortPolicy();
75
76     private boolean exposeUnconfigurableExecutor = false;
77
78     private ScheduledExecutorService executor;
79
80
81     /**
82      * Register a list of ScheduledExecutorTask objects with the ScheduledExecutorService
83      * that this FactoryBean creates. Depending on each ScheduledExecutorTask's settings,
84      * it will be registered via one of ScheduledExecutorService's schedule methods.
85      * @see edu.emory.mathcs.backport.java.util.concurrent.ScheduledExecutorService#schedule(java.lang.Runnable, long, edu.emory.mathcs.backport.java.util.concurrent.TimeUnit)
86      * @see edu.emory.mathcs.backport.java.util.concurrent.ScheduledExecutorService#scheduleWithFixedDelay(java.lang.Runnable, long, long, edu.emory.mathcs.backport.java.util.concurrent.TimeUnit)
87      * @see edu.emory.mathcs.backport.java.util.concurrent.ScheduledExecutorService#scheduleAtFixedRate(java.lang.Runnable, long, long, edu.emory.mathcs.backport.java.util.concurrent.TimeUnit)
88      */

89     public void setScheduledExecutorTasks(ScheduledExecutorTask[] scheduledExecutorTasks) {
90         this.scheduledExecutorTasks = scheduledExecutorTasks;
91     }
92
93     /**
94      * Set the ScheduledExecutorService's pool size.
95      * Default is 1.
96      */

97     public void setPoolSize(int poolSize) {
98         Assert.isTrue(poolSize > 0, "'poolSize' must be 1 or higher");
99         this.poolSize = poolSize;
100     }
101
102     /**
103      * Set the ThreadFactory to use for the ThreadPoolExecutor's thread pool.
104      * Default is the ThreadPoolExecutor's default thread factory.
105      * @see edu.emory.mathcs.backport.java.util.concurrent.Executors#defaultThreadFactory()
106      */

107     public void setThreadFactory(ThreadFactory threadFactory) {
108         this.threadFactory = (threadFactory != null ? threadFactory : Executors.defaultThreadFactory());
109     }
110
111     /**
112      * Set the RejectedExecutionHandler to use for the ThreadPoolExecutor.
113      * Default is the ThreadPoolExecutor's default abort policy.
114      * @see edu.emory.mathcs.backport.java.util.concurrent.ThreadPoolExecutor.AbortPolicy
115      */

116     public void setRejectedExecutionHandler(RejectedExecutionHandler rejectedExecutionHandler) {
117         this.rejectedExecutionHandler =
118                 (rejectedExecutionHandler != null ? rejectedExecutionHandler : new ThreadPoolExecutor.AbortPolicy());
119     }
120
121     /**
122      * Specify whether this FactoryBean should expose an unconfigurable
123      * decorator for the created executor.
124      * <p>Default is "false", exposing the raw executor as bean reference.
125      * Switch this flag to "true" to strictly prevent clients from
126      * modifying the executor's configuration.
127      * @see edu.emory.mathcs.backport.java.util.concurrent.Executors#unconfigurableScheduledExecutorService
128      */

129     public void setExposeUnconfigurableExecutor(boolean exposeUnconfigurableExecutor) {
130         this.exposeUnconfigurableExecutor = exposeUnconfigurableExecutor;
131     }
132
133
134     public void afterPropertiesSet() {
135         logger.info("Initializing SchedulerExecutorService");
136         ScheduledExecutorService executor =
137                 createExecutor(this.poolSize, this.threadFactory, this.rejectedExecutionHandler);
138
139         // Register specified ScheduledExecutorTasks, if necessary.
140
if (!ObjectUtils.isEmpty(this.scheduledExecutorTasks)) {
141             registerTasks(this.scheduledExecutorTasks, executor);
142         }
143
144         // Wrap executor with an unconfigurable decorator.
145
this.executor = (this.exposeUnconfigurableExecutor ?
146                 Executors.unconfigurableScheduledExecutorService(executor) : executor);
147     }
148
149     /**
150      * Create a new {@link ScheduledExecutorService} instance.
151      * Called by <code>afterPropertiesSet</code>.
152      * <p>Default implementation creates a {@link ScheduledThreadPoolExecutor}.
153      * Can be overridden in subclasses to provide custom
154      * {@link ScheduledExecutorService} instances.
155      * @param poolSize the specified pool size
156      * @param threadFactory the ThreadFactory to use
157      * @param rejectedExecutionHandler the RejectedExecutionHandler to use
158      * @return a new ScheduledExecutorService instance
159      * @see #afterPropertiesSet()
160      * @see edu.emory.mathcs.backport.java.util.concurrent.ScheduledThreadPoolExecutor
161      */

162     protected ScheduledExecutorService createExecutor(
163             int poolSize, ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) {
164
165         return new ScheduledThreadPoolExecutor(poolSize, threadFactory, rejectedExecutionHandler);
166     }
167
168     /**
169      * Register the specified {@link ScheduledExecutorTask ScheduledExecutorTasks}
170      * on the given {@link ScheduledExecutorService}.
171      * @param tasks the specified ScheduledExecutorTasks (never empty)
172      * @param executor the ScheduledExecutorService to register the tasks on.
173      */

174     protected void registerTasks(ScheduledExecutorTask[] tasks, ScheduledExecutorService executor) {
175         for (int i = 0; i < tasks.length; i++) {
176             ScheduledExecutorTask task = tasks[i];
177             if (task.isOneTimeTask()) {
178                 executor.schedule(task.getRunnable(), task.getDelay(), task.getTimeUnit());
179             }
180             else {
181                 if (task.isFixedRate()) {
182                     executor.scheduleAtFixedRate(
183                             task.getRunnable(), task.getDelay(), task.getPeriod(), task.getTimeUnit());
184                 }
185                 else {
186                     executor.scheduleWithFixedDelay(
187                             task.getRunnable(), task.getDelay(), task.getPeriod(), task.getTimeUnit());
188                 }
189             }
190         }
191     }
192
193
194     public Object JavaDoc getObject() {
195         return this.executor;
196     }
197
198     public Class JavaDoc getObjectType() {
199         return (this.executor != null ? this.executor.getClass() : ScheduledExecutorService.class);
200     }
201
202     public boolean isSingleton() {
203         return true;
204     }
205
206
207     /**
208      * Cancel the ScheduledExecutorService on bean factory shutdown,
209      * stopping all scheduled tasks.
210      * @see edu.emory.mathcs.backport.java.util.concurrent.ScheduledExecutorService#shutdown()
211      */

212     public void destroy() {
213         logger.info("Shutting down ScheduledExecutorService");
214         this.executor.shutdown();
215     }
216
217 }
218
Popular Tags