2018-04-05

Java EE7 ScheduledManagedExecutorService

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!-- weblogic.xml -->
<wls:work-manager>
 <wls:name>CustomWorkManager</wls:name>
 <wls:min-threads-constraint>
  <wls:name>MINTHREAD</wls:name>
  <wls:count>10</wls:count>
 </wls:min-threads-constraint>
 <wls:max-threads-constraint>
  <wls:name>MAXTHREAD</wls:name>
  <wls:count>150</wls:count>
 </wls:max-threads-constraint>
 <wls:capacity>
  <wls:name>MAXCAPACITY</wls:name>
  <wls:count>10000</wls:count>
 </wls:capacity>
</wls:work-manager>
 
<wls:managed-scheduled-executor-service>
 <wls:name>FooSMES</wls:name>
 <wls:dispatch-policy>CustomWorkManager</wls:dispatch-policy>
 <wls:max-concurrent-long-running-requests>10</wls:max-concurrent-long-running-requests>
</wls:managed-scheduled-executor-service>
 
<wls:resource-env-description>
 <wls:resource-env-ref-name>concurrent/FooSMES</wls:resource-env-ref-name>
 <wls:resource-link>FooSMES</wls:resource-link>
</wls:resource-env-description>
1
2
3
4
5
<!-- web.xml -->
<resource-env-ref>
 <resource-env-ref-name>concurrent/FooSMES</resource-env-ref-name>
 <resource-env-ref-type>javax.enterprise.concurrent.ManagedScheduledExecutorService</resource-env-ref-type>
</resource-env-ref>
1
2
3
4
5
6
7
8
9
10
ScheduledExecutorService mySMES = InitialContext.doLookup("java:comp/env/concurrent/FooSMES");
 
ScheduledFuture<?> future = mySMES.scheduleAtFixedRate(SomeClass::someMethod, 0, 5, TimeUnit.MINUTES);
// Starts immediately (delay 0 minutes), run every 5 minutes.
 
// How to stop:
if (!future.isCancelled()) {
 future.cancel(true);
}
// true == If the Runnable is running at the moment, the Thread will likely receive an interrupt.
1
2
3
4
5
6
7
8
9
10
11
// Inside SomeClass's someMethod method.
 
// How to handle thread interruption:
// 1) Periodically check Thread.interrupted(). If it's true, please quickly clean up, and then return.
// 2) catch InterruptedException -- this is not available at all places.
 
// Example:
while(!Thread.interrupted()) {
 // Do repetitive tasks that took very long if you consider all the iterations combined.
}
// We get here when interrupted. Clean up everything and leave.

No comments :

Post a Comment