KickJava   Java API By Example, From Geeks To Geeks.

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

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

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

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

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

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

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

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

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

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