Skip to content

Commit 4004e53

Browse files
committed
JSR-236 support, in particular adapting to JSR-236 Triggers and exposing additional metadata through ManagedTasks
This is built into ConcurrentTaskExecutor and ConcurrentTaskScheduler now, automatically detecting the JSR-236 ExecutorService variants and adapting to them. Issue: SPR-8195
1 parent 52fd84b commit 4004e53

5 files changed

Lines changed: 220 additions & 38 deletions

File tree

‎spring-context/src/main/java/org/springframework/scheduling/concurrent/ConcurrentTaskExecutor.java‎

Lines changed: 97 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2012 the original author or authors.
2+
* Copyright 2002-2013 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -16,20 +16,31 @@
1616

1717
package org.springframework.scheduling.concurrent;
1818

19+
import java.util.HashMap;
20+
import java.util.Map;
1921
import java.util.concurrent.Callable;
2022
import java.util.concurrent.Executor;
2123
import java.util.concurrent.Executors;
2224
import java.util.concurrent.Future;
25+
import javax.enterprise.concurrent.ManagedExecutors;
26+
import javax.enterprise.concurrent.ManagedTask;
2327

2428
import org.springframework.core.task.support.TaskExecutorAdapter;
29+
import org.springframework.scheduling.SchedulingAwareRunnable;
2530
import org.springframework.scheduling.SchedulingTaskExecutor;
31+
import org.springframework.util.ClassUtils;
2632

2733
/**
2834
* Adapter that takes a JDK 1.5 {@code java.util.concurrent.Executor} and
2935
* exposes a Spring {@link org.springframework.core.task.TaskExecutor} for it.
3036
* Also detects an extended {@code java.util.concurrent.ExecutorService}, adapting
3137
* the {@link org.springframework.core.task.AsyncTaskExecutor} interface accordingly.
3238
*
39+
* <p>Autodetects a JSR-236 {@link javax.enterprise.concurrent.ManagedExecutorService}
40+
* in order to expose {@link javax.enterprise.concurrent.ManagedTask} adapters for it,
41+
* exposing a long-running hint based on {@link SchedulingAwareRunnable} and an
42+
* identity name based on the given Runnable/Callable's {@code toString()}.
43+
*
3344
* <p>Note that there is a pre-built {@link ThreadPoolTaskExecutor} that allows for
3445
* defining a JDK 1.5 {@link java.util.concurrent.ThreadPoolExecutor} in bean style,
3546
* exposing it as a Spring {@link org.springframework.core.task.TaskExecutor} directly.
@@ -46,6 +57,20 @@
4657
*/
4758
public class ConcurrentTaskExecutor implements SchedulingTaskExecutor {
4859

60+
private static Class<?> managedExecutorService;
61+
62+
static {
63+
try {
64+
managedExecutorService = ClassUtils.forName(
65+
"javax.enterprise.concurrent.ManagedExecutorService",
66+
ConcurrentTaskScheduler.class.getClassLoader());
67+
}
68+
catch (ClassNotFoundException ex) {
69+
// JSR-236 API not available...
70+
managedExecutorService = null;
71+
}
72+
}
73+
4974
private Executor concurrentExecutor;
5075

5176
private TaskExecutorAdapter adaptedExecutor;
@@ -63,6 +88,8 @@ public ConcurrentTaskExecutor() {
6388
/**
6489
* Create a new ConcurrentTaskExecutor,
6590
* using the given JDK 1.5 concurrent executor.
91+
* <p>Autodetects a JSR-236 {@link javax.enterprise.concurrent.ManagedExecutorService}
92+
* in order to expose {@link javax.enterprise.concurrent.ManagedTask} adapters for it.
6693
* @param concurrentExecutor the JDK 1.5 concurrent executor to delegate to
6794
*/
6895
public ConcurrentTaskExecutor(Executor concurrentExecutor) {
@@ -72,11 +99,23 @@ public ConcurrentTaskExecutor(Executor concurrentExecutor) {
7299

73100
/**
74101
* Specify the JDK 1.5 concurrent executor to delegate to.
102+
* <p>Autodetects a JSR-236 {@link javax.enterprise.concurrent.ManagedExecutorService}
103+
* in order to expose {@link javax.enterprise.concurrent.ManagedTask} adapters for it.
75104
*/
76105
public final void setConcurrentExecutor(Executor concurrentExecutor) {
77-
this.concurrentExecutor =
78-
(concurrentExecutor != null ? concurrentExecutor : Executors.newSingleThreadExecutor());
79-
this.adaptedExecutor = new TaskExecutorAdapter(this.concurrentExecutor);
106+
if (concurrentExecutor != null) {
107+
this.concurrentExecutor = concurrentExecutor;
108+
if (managedExecutorService != null && managedExecutorService.isInstance(concurrentExecutor)) {
109+
this.adaptedExecutor = new ManagedTaskExecutorAdapter(concurrentExecutor);
110+
}
111+
else {
112+
this.adaptedExecutor = new TaskExecutorAdapter(concurrentExecutor);
113+
}
114+
}
115+
else {
116+
this.concurrentExecutor = Executors.newSingleThreadExecutor();
117+
this.adaptedExecutor = new TaskExecutorAdapter(this.concurrentExecutor);
118+
}
80119
}
81120

82121
/**
@@ -110,4 +149,58 @@ public boolean prefersShortLivedTasks() {
110149
return true;
111150
}
112151

152+
153+
/**
154+
* TaskExecutorAdapter subclass that wraps all provided Runnables and Callables
155+
* with a JSR-236 ManagedTask, exposing a long-running hint based on
156+
* {@link SchedulingAwareRunnable} and an identity name based on the task's
157+
* {@code toString()} representation.
158+
*/
159+
private static class ManagedTaskExecutorAdapter extends TaskExecutorAdapter {
160+
161+
public ManagedTaskExecutorAdapter(Executor concurrentExecutor) {
162+
super(concurrentExecutor);
163+
}
164+
165+
@Override
166+
public void execute(Runnable task) {
167+
super.execute(ManagedTaskBuilder.buildManagedTask(task, task.toString()));
168+
}
169+
170+
@Override
171+
public Future<?> submit(Runnable task) {
172+
return super.submit(ManagedTaskBuilder.buildManagedTask(task, task.toString()));
173+
}
174+
175+
@Override
176+
public <T> Future<T> submit(Callable<T> task) {
177+
return super.submit(ManagedTaskBuilder.buildManagedTask(task, task.toString()));
178+
}
179+
}
180+
181+
182+
/**
183+
* Delegate that wraps a given Runnable/Callable with a JSR-236 ManagedTask,
184+
* exposing a long-running hint based on {@link SchedulingAwareRunnable}
185+
* and a given identity name.
186+
*/
187+
protected static class ManagedTaskBuilder {
188+
189+
public static Runnable buildManagedTask(Runnable task, String identityName) {
190+
Map<String, String> properties = new HashMap<String, String>(2);
191+
if (task instanceof SchedulingAwareRunnable) {
192+
properties.put(ManagedTask.LONGRUNNING_HINT,
193+
Boolean.toString(((SchedulingAwareRunnable) task).isLongLived()));
194+
}
195+
properties.put(ManagedTask.IDENTITY_NAME, identityName);
196+
return ManagedExecutors.managedTask(task, properties, null);
197+
}
198+
199+
public static <T> Callable<T> buildManagedTask(Callable<T> task, String identityName) {
200+
Map<String, String> properties = new HashMap<String, String>(1);
201+
properties.put(ManagedTask.IDENTITY_NAME, identityName);
202+
return ManagedExecutors.managedTask(task, properties, null);
203+
}
204+
}
205+
113206
}

‎spring-context/src/main/java/org/springframework/scheduling/concurrent/ConcurrentTaskScheduler.java‎

Lines changed: 86 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2012 the original author or authors.
2+
* Copyright 2002-2013 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -23,12 +23,16 @@
2323
import java.util.concurrent.ScheduledExecutorService;
2424
import java.util.concurrent.ScheduledFuture;
2525
import java.util.concurrent.TimeUnit;
26+
import javax.enterprise.concurrent.LastExecution;
27+
import javax.enterprise.concurrent.ManagedScheduledExecutorService;
2628

2729
import org.springframework.core.task.TaskRejectedException;
2830
import org.springframework.scheduling.TaskScheduler;
2931
import org.springframework.scheduling.Trigger;
32+
import org.springframework.scheduling.support.SimpleTriggerContext;
3033
import org.springframework.scheduling.support.TaskUtils;
3134
import org.springframework.util.Assert;
35+
import org.springframework.util.ClassUtils;
3236
import org.springframework.util.ErrorHandler;
3337

3438
/**
@@ -37,6 +41,11 @@
3741
* Extends {@link ConcurrentTaskExecutor} in order to implement the
3842
* {@link org.springframework.scheduling.SchedulingTaskExecutor} interface as well.
3943
*
44+
* <p>Autodetects a JSR-236 {@link javax.enterprise.concurrent.ManagedScheduledExecutorService}
45+
* in order to use it for trigger-based scheduling if possible, instead of Spring's
46+
* local trigger management which ends up delegating to regular delay-based scheduling
47+
* against the {@code java.util.concurrent.ScheduledExecutorService} API.
48+
*
4049
* <p>Note that there is a pre-built {@link ThreadPoolTaskScheduler} that allows for
4150
* defining a JDK 1.5 {@link java.util.concurrent.ScheduledThreadPoolExecutor} in bean style,
4251
* exposing it as a Spring {@link org.springframework.scheduling.TaskScheduler} directly.
@@ -53,9 +62,25 @@
5362
*/
5463
public class ConcurrentTaskScheduler extends ConcurrentTaskExecutor implements TaskScheduler {
5564

56-
private volatile ScheduledExecutorService scheduledExecutor;
65+
private static Class<?> managedScheduledExecutorService;
5766

58-
private volatile ErrorHandler errorHandler;
67+
static {
68+
try {
69+
managedScheduledExecutorService = ClassUtils.forName(
70+
"javax.enterprise.concurrent.ManagedScheduledExecutorService",
71+
ConcurrentTaskScheduler.class.getClassLoader());
72+
}
73+
catch (ClassNotFoundException ex) {
74+
// JSR-236 API not available...
75+
managedScheduledExecutorService = null;
76+
}
77+
}
78+
79+
private ScheduledExecutorService scheduledExecutor;
80+
81+
private boolean enterpriseConcurrentScheduler = false;
82+
83+
private ErrorHandler errorHandler;
5984

6085

6186
/**
@@ -71,6 +96,9 @@ public ConcurrentTaskScheduler() {
7196
/**
7297
* Create a new ConcurrentTaskScheduler,
7398
* using the given JDK 1.5 executor as shared delegate.
99+
* <p>Autodetects a JSR-236 {@link javax.enterprise.concurrent.ManagedScheduledExecutorService}
100+
* in order to use it for trigger-based scheduling if possible,
101+
* instead of Spring's local trigger management.
74102
* @param scheduledExecutor the JDK 1.5 scheduled executor to delegate to
75103
* for {@link org.springframework.scheduling.SchedulingTaskExecutor} as well
76104
* as {@link TaskScheduler} invocations
@@ -83,6 +111,9 @@ public ConcurrentTaskScheduler(ScheduledExecutorService scheduledExecutor) {
83111
/**
84112
* Create a new ConcurrentTaskScheduler,
85113
* using the given JDK 1.5 executors as delegates.
114+
* <p>Autodetects a JSR-236 {@link javax.enterprise.concurrent.ManagedScheduledExecutorService}
115+
* in order to use it for trigger-based scheduling if possible,
116+
* instead of Spring's local trigger management.
86117
* @param concurrentExecutor the JDK 1.5 concurrent executor to delegate to
87118
* for {@link org.springframework.scheduling.SchedulingTaskExecutor} invocations
88119
* @param scheduledExecutor the JDK 1.5 scheduled executor to delegate to
@@ -96,15 +127,25 @@ public ConcurrentTaskScheduler(Executor concurrentExecutor, ScheduledExecutorSer
96127

97128
/**
98129
* Specify the JDK 1.5 scheduled executor to delegate to.
130+
* <p>Autodetects a JSR-236 {@link javax.enterprise.concurrent.ManagedScheduledExecutorService}
131+
* in order to use it for trigger-based scheduling if possible,
132+
* instead of Spring's local trigger management.
99133
* <p>Note: This will only apply to {@link TaskScheduler} invocations.
100134
* If you want the given executor to apply to
101135
* {@link org.springframework.scheduling.SchedulingTaskExecutor} invocations
102136
* as well, pass the same executor reference to {@link #setConcurrentExecutor}.
103137
* @see #setConcurrentExecutor
104138
*/
105139
public final void setScheduledExecutor(ScheduledExecutorService scheduledExecutor) {
106-
this.scheduledExecutor =
107-
(scheduledExecutor != null ? scheduledExecutor : Executors.newSingleThreadScheduledExecutor());
140+
if (scheduledExecutor != null) {
141+
this.scheduledExecutor = scheduledExecutor;
142+
this.enterpriseConcurrentScheduler = (managedScheduledExecutorService != null &&
143+
managedScheduledExecutorService.isInstance(scheduledExecutor));
144+
}
145+
else {
146+
this.scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
147+
this.enterpriseConcurrentScheduler = false;
148+
}
108149
}
109150

110151
/**
@@ -118,9 +159,13 @@ public void setErrorHandler(ErrorHandler errorHandler) {
118159

119160
public ScheduledFuture schedule(Runnable task, Trigger trigger) {
120161
try {
121-
ErrorHandler errorHandler =
122-
(this.errorHandler != null ? this.errorHandler : TaskUtils.getDefaultErrorHandler(true));
123-
return new ReschedulingRunnable(task, trigger, this.scheduledExecutor, errorHandler).schedule();
162+
if (this.enterpriseConcurrentScheduler) {
163+
return new EnterpriseConcurrentTriggerScheduler().schedule(decorateTask(task, true), trigger);
164+
}
165+
else {
166+
ErrorHandler errorHandler = (this.errorHandler != null ? this.errorHandler : TaskUtils.getDefaultErrorHandler(true));
167+
return new ReschedulingRunnable(task, trigger, this.scheduledExecutor, errorHandler).schedule();
168+
}
124169
}
125170
catch (RejectedExecutionException ex) {
126171
throw new TaskRejectedException("Executor [" + this.scheduledExecutor + "] did not accept task: " + task, ex);
@@ -130,8 +175,7 @@ public ScheduledFuture schedule(Runnable task, Trigger trigger) {
130175
public ScheduledFuture schedule(Runnable task, Date startTime) {
131176
long initialDelay = startTime.getTime() - System.currentTimeMillis();
132177
try {
133-
return this.scheduledExecutor.schedule(
134-
errorHandlingTask(task, false), initialDelay, TimeUnit.MILLISECONDS);
178+
return this.scheduledExecutor.schedule(decorateTask(task, false), initialDelay, TimeUnit.MILLISECONDS);
135179
}
136180
catch (RejectedExecutionException ex) {
137181
throw new TaskRejectedException("Executor [" + this.scheduledExecutor + "] did not accept task: " + task, ex);
@@ -141,8 +185,7 @@ public ScheduledFuture schedule(Runnable task, Date startTime) {
141185
public ScheduledFuture scheduleAtFixedRate(Runnable task, Date startTime, long period) {
142186
long initialDelay = startTime.getTime() - System.currentTimeMillis();
143187
try {
144-
return this.scheduledExecutor.scheduleAtFixedRate(
145-
errorHandlingTask(task, true), initialDelay, period, TimeUnit.MILLISECONDS);
188+
return this.scheduledExecutor.scheduleAtFixedRate(decorateTask(task, true), initialDelay, period, TimeUnit.MILLISECONDS);
146189
}
147190
catch (RejectedExecutionException ex) {
148191
throw new TaskRejectedException("Executor [" + this.scheduledExecutor + "] did not accept task: " + task, ex);
@@ -151,8 +194,7 @@ public ScheduledFuture scheduleAtFixedRate(Runnable task, Date startTime, long p
151194

152195
public ScheduledFuture scheduleAtFixedRate(Runnable task, long period) {
153196
try {
154-
return this.scheduledExecutor.scheduleAtFixedRate(
155-
errorHandlingTask(task, true), 0, period, TimeUnit.MILLISECONDS);
197+
return this.scheduledExecutor.scheduleAtFixedRate(decorateTask(task, true), 0, period, TimeUnit.MILLISECONDS);
156198
}
157199
catch (RejectedExecutionException ex) {
158200
throw new TaskRejectedException("Executor [" + this.scheduledExecutor + "] did not accept task: " + task, ex);
@@ -162,8 +204,7 @@ public ScheduledFuture scheduleAtFixedRate(Runnable task, long period) {
162204
public ScheduledFuture scheduleWithFixedDelay(Runnable task, Date startTime, long delay) {
163205
long initialDelay = startTime.getTime() - System.currentTimeMillis();
164206
try {
165-
return this.scheduledExecutor.scheduleWithFixedDelay(
166-
errorHandlingTask(task, true), initialDelay, delay, TimeUnit.MILLISECONDS);
207+
return this.scheduledExecutor.scheduleWithFixedDelay(decorateTask(task, true), initialDelay, delay, TimeUnit.MILLISECONDS);
167208
}
168209
catch (RejectedExecutionException ex) {
169210
throw new TaskRejectedException("Executor [" + this.scheduledExecutor + "] did not accept task: " + task, ex);
@@ -172,16 +213,41 @@ public ScheduledFuture scheduleWithFixedDelay(Runnable task, Date startTime, lon
172213

173214
public ScheduledFuture scheduleWithFixedDelay(Runnable task, long delay) {
174215
try {
175-
return this.scheduledExecutor.scheduleWithFixedDelay(
176-
errorHandlingTask(task, true), 0, delay, TimeUnit.MILLISECONDS);
216+
return this.scheduledExecutor.scheduleWithFixedDelay(decorateTask(task, true), 0, delay, TimeUnit.MILLISECONDS);
177217
}
178218
catch (RejectedExecutionException ex) {
179219
throw new TaskRejectedException("Executor [" + this.scheduledExecutor + "] did not accept task: " + task, ex);
180220
}
181221
}
182222

183-
private Runnable errorHandlingTask(Runnable task, boolean isRepeatingTask) {
184-
return TaskUtils.decorateTaskWithErrorHandler(task, this.errorHandler, isRepeatingTask);
223+
private Runnable decorateTask(Runnable task, boolean isRepeatingTask) {
224+
Runnable result = TaskUtils.decorateTaskWithErrorHandler(task, this.errorHandler, isRepeatingTask);
225+
if (this.enterpriseConcurrentScheduler) {
226+
result = ManagedTaskBuilder.buildManagedTask(result, task.toString());
227+
}
228+
return result;
229+
}
230+
231+
232+
/**
233+
* Delegate that adapts a Spring Trigger to a JSR-236 Trigger.
234+
* Separated into an inner class in order to avoid a hard dependency on the JSR-236 API.
235+
*/
236+
private class EnterpriseConcurrentTriggerScheduler {
237+
238+
public ScheduledFuture schedule(Runnable task, final Trigger trigger) {
239+
ManagedScheduledExecutorService executor = (ManagedScheduledExecutorService) scheduledExecutor;
240+
return executor.schedule(task, new javax.enterprise.concurrent.Trigger() {
241+
public Date getNextRunTime(LastExecution le, Date taskScheduledTime) {
242+
return trigger.nextExecutionTime(le != null ?
243+
new SimpleTriggerContext(le.getScheduledStart(), le.getRunStart(), le.getRunEnd()) :
244+
new SimpleTriggerContext());
245+
}
246+
public boolean skipRun(LastExecution lastExecution, Date scheduledRunTime) {
247+
return false;
248+
}
249+
});
250+
}
185251
}
186252

187253
}

‎spring-context/src/main/java/org/springframework/scheduling/concurrent/ExecutorConfigurationSupport.java‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,11 @@ public abstract class ExecutorConfigurationSupport extends CustomizableThreadFac
6565
/**
6666
* Set the ThreadFactory to use for the ThreadPoolExecutor's thread pool.
6767
* Default is the ThreadPoolExecutor's default thread factory.
68+
* <p>In a Java EE 7 or other managed environment with JSR-236 support,
69+
* consider specifying a JNDI-located ManagedThreadFactory: by default,
70+
* to be found at "java:comp/env/concurrent/tf/DefaultThreadFactory".
71+
* Use the "jee:jndi-lookup" namespace element in XML or the programmatic
72+
* {@link org.springframework.jndi.JndiLocatorDelegate} for convenient lookup.
6873
* @see java.util.concurrent.Executors#defaultThreadFactory()
6974
*/
7075
public void setThreadFactory(ThreadFactory threadFactory) {

0 commit comments

Comments
 (0)