7 Configuring Concurrent Managed Objects

This chapter describes the Concurrent Managed Objects (CMOs) implemented by WebLogic Server to provide support for defining and implementing the Concurrency Utilities for Java EE 1.0 (JSR 236).

This chapter includes the following sections:

About Java EE Concurrency Utilities

The Concurrency Utilities for Java EE 1.0 (JSR 236) implements a standard API for providing asynchronous capabilities to Java EE application components, such as servlets and EJBs.

As described in the Java EE 7 Tutorial, the two main concurrency concepts are processes and threads:

  • Processes are primarily associated with applications running on the operating system (OS). A process has specific runtime resources to interact with the underlying OS and allocate other resources, such as its own memory, just as the JVM process does. A JVM is in fact a process.

  • Threads share some features with processes, since both consume resources from the OS or the execution environment. But threads are easier to create and consume many fewer resources than a process.

The primary components of the concurrency utilities are:

  • ManagedExecutorService (MES): Used by applications to execute submitted tasks asynchronously. Tasks are executed on threads that are started and managed by the container. The context of the container is propagated to the thread executing the task.

  • ManagedScheduledExecutorService (MSES): Used by applications to execute submitted tasks asynchronously at specific times. Tasks are executed on threads that are started and managed by the container. The context of the container is propagated to the thread executing the task.

  • ManagedThreadFactory (MTF): Used by applications to create managed threads. The threads are started and managed by the container. The context of the container is propagated to the thread executing the task.

  • ContextService: Used to create dynamic proxy objects that capture the context of a container and enable applications to run within that context at a later time or be submitted to a Managed Executor Service. The context of the container is propagated to the thread executing the task.

For more detailed information, see "Concurrency Utilities for Java EE" in The Java EE 7 Tutorial. Also see the Java Specification Request 236: Concurrency Utilities for Java EE 1.0 (http://jcp.org/en/jsr/detail?id=236).

Concurrency 1.0 Code Examples in WebLogic Server

When you install WebLogic Server complete with the examples, the examples source code is placed in the EXAMPLES_HOME\examples\src\examples directory. The default path is ORACLE_HOME\wlserver\samples\server. From this directory, you can access the source code and instruction files for the Concurrency 1.0 examples without having to set up the samples domain.

The ORACLE_HOME\user_projects\domains\wl_server directory contains the WebLogic Server examples domain; it contains your applications and the XML configuration files that define how your applications and Oracle WebLogic Server will behave, as well as startup and environment scripts. For more information about the WebLogic Server code examples, see Sample Applications and Code Examples in Understanding Oracle WebLogic Server.

  • Using Concurrency ContextService – demonstrates how to use ContextService interface to create dynamic proxy objects.

    EXAMPLES_HOME/wl_server/examples/src/examples/javaee7/concurrency/dynamicproxy
    
  • Using Concurrency Executor – demonstrates how to use javax.enterprise.concurrent.ManagedExecutorService for submitting tasks.

    EXAMPLES_HOME/examples/src/examples/javaee7/concurrency/executor
    
  • Using Concurrency Schedule – demonstrates how to use javax.enterprise.concurrent.ManagedScheduledExecutorService for submitting delayed or periodic tasks.

    EXAMPLES_HOME/examples/src/examples/javaee7/concurrency/schedule
    
  • Using Concurrency Threads – demonstrates how to use javax.enterprise.concurrent.ManagedThreadFactory to obtain a thread from the Java EE container.

    EXAMPLES_HOME/examples/src/examples/javaee7/concurrency/threads
    

Oracle recommends that you run these examples before programming your own applications that use concurrency.

How Concurrent Managed Objects Provide Concurrency for WebLogic Server Containers

This section discusses how WebLogic Server provides concurrency capabilities to Java EE applications by associating the Concurrency Utilities API with the Work Manager to make threads container-managed.

How WebLogic Server Handles Asynchronous Tasks in Application Components

With JSR236 Concurrent Utilities, WebLogic Server can recognize the asynchronous tasks in a server application component, and then manages them by:

Concurrent Managed Objects (CMOs)

In WebLogic Server, asynchronous task management is provided by four types of Concurrent Managed Objects (or CMOs).

Table 7-1 summarizes the CMOs that provide asynchronous task management.


Table 7-1 CMOs that Provide Asynchronous Task Management

Managed Object Context Propagation Self Tuning Thread Interruption While Shutting Down Limit of Concurrent Long-Running New Threads

Managed Executor Service (MES)

Contexts are propagated based on configuration. See CMO Context Propagation.

Only short-running tasks are dispatched to the single self-tuning thread pool by a specified work manager. See Self Tuning for CMO Tasks.

When Work Manager is shutting down, all the unfinished task will be canceled. See Threads Interruption When CMOs Are Shutting Down.

The maximum number of long-running threads created by MES/MSES can be configured to avoid excessive number of these threads making negative effect on server. See CMO Constraints for Long-Running Threads.

Managed Scheduled Executor Service (MSES)

Contexts are propagated based on configuration. See CMO Context Propagation.

Same behavior as MES. See Self Tuning for CMO Tasks.

Same behavior as MES. See Threads Interruption When CMOs Are Shutting Down.

Same behavior as MES. See CMO Constraints for Long-Running Threads.

Context Service

Contexts are propagated based on configuration. See CMO Context Propagation.

n/a

n/a

n/a

Managed Thread Factory (MTF)

Contexts are propagated based on configuration. See CMO Context Propagation.

Threads returned by the newThread() method are not from the single self-tuning thread pool and will not be put into the thread pool when the task is finished. See Self Tuning for CMO Tasks.

Threads created by the newThread() method will be interrupted when the MTF is shutting down. See Threads Interruption When CMOs Are Shutting Down.

The maximum number of new threads created by MTF can be configured to avoid excessive number of these threads making negative effect on server. See CMO Constraints for Long-Running Threads.


There are three types of JSR236 CMOs in WebLogic Server, each one characterized by its scope and how it is defined and used.

  • Default Java EE CMOs – Required by the Java EE standard that default resources be made available to applications, and defines specific JNDI names for these default resources.

  • Customized CMOs in Configuration Files – Can be defined at the application and module level or referenced from an application component environment (ENC) that is bound to JNDI.

  • Global CMO Templates – Can be defined globally as templates in the domain's configuration by using the WebLogic Server Administration Console and configuration MBeans.

Similar to Work Managers, global CMO templates can be defined at the domain or server level using the WebLogic Server Administration Console or configuration MBeans. For more information see, Configuring CMO Templates using the Administration Console and Using MBeans to Configure CMO Templates.

CMOs versus CommonJ API

The CommonJ API (commonj.work) in WebLogic Server provides a set of interfaces that allows an application to execute multiple work items concurrently within a container. CMOs and CommonJ APIs operate at the same level: they both dispatch tasks to work managers and programmatically handle work from within an application. However, there are distinct differences between CMOs and the CommonJ API, such as:

  • CommonJ API is Weblogic specific and CMOs have been standardized.

  • CommonJ API provides functions similar to the CMO Managed Executor Service and Managed Scheduled Executor Service, but it does not provides CMO functions like the Managed Thread Factory and the Context Service.

For information about using the CommonJ API, see Using the Timer and Work Manager API in Developing CommonJ Applications for Oracle WebLogic Server.

CMO Context Propagation

This section explains the four context types that are propagated for CMOs and the context invocation points in WebLogic Server for MES and MSES managed objects.

Propagated Context Types

Table 7-2 summarizes the contexts types that are propagated for the four types of managed objects.


Table 7-2 Propagated Context Types

Context Type Description Context Tasks Run with...

JNDI

JNDI namespace

For MES, MSES, and ContextService, tasks can access the application-scoped JNDI tree (such as java:app, java:module, java:comp) of the submitting thread.

For MTF, tasks can access application-scoped JNDI tree of the component that created the ManagedThreadFactory instance.

ClassLoader

Context Class loader

For MES, MSES, and ContextService, tasks run with the context classloader of the submitting thread.

For MTF, tasks run with the classloader of the component that created the ManagedThreadFactory instance

Security

Subject identity

For MES, MSES, and ContextService, tasks run with the subject identity of the submitting thread.For MTF, tasks run with the anonymous subject.

WorkArea

WorkArea contexts with PropagationMode WORK

For MES, MSES, and Context Service there is a new WorkArea context type, and so all tasks run with a WorkContextMap, which contains all the submitting thread's contexts with WORK mode.

For MTF, all tasks run with an empty WorkContextMap.

Note: While the WorkContextMap is a new instance, the contained values are not, so updating the contents of the values can affect the contents of the submitting thread.


Contextual Invocation Points

Table 7-3 summarizes the callback methods of the Contextual Invocation Points in WebLogic Server and the context that the Contextual Invocation Point runs with for the MES and MSES managed objects.


Table 7-3 Contextual Invocation Points

Concurrent Managed Objects Contextual Invocation Points Context with which the Contextual Invocation Point Runs

ManagedExecutorService

callback method: javax.enterprise.concurrent.ManagedTaskListener

The Contextual Invocation Points run with the context of the application component instance that called the submit(), invokeAll(), invokeAny() methods.

ManagedScheduledExecutorService

callback methods: javax.enterprise.concurrent.ManagedTaskListener and javax.enterprise.concurrent.Trigger

The application component instance that called the submit(), invokeAll(), invokeAny(), schedule(), scheduleAtFixedRate(), scheduleWithFixedDelay() methods.


Self Tuning for CMO Tasks

Short-running tasks submitted to the MES or the MSES are dispatched to the single self-tuning thread pool by associating with the Work Manager specified in deployment descriptors.

The execution of the tasks will be consistent with the rules defined for the specified Work Manager. For tasks submitted to the execute method in MES and MSES, if the Work Manager's overload policy rejects the task, the following events will occur:

  • The java.util.concurrent.RejectedExecutionException will be thrown in the submit or execute method.

  • The overload reason parameter passed to weblogic.work.Work will be set to the RejectedExecutionException.

  • If the user registered the task with the ManagedTaskListener, this listener will not be notified because user can receive the overload message through the RejectedExecutionException.

    Note: A ManagedTaskListener is used to monitor the state of a task's Future. For more information see, Package javax.enterprise.concurrent.

For the invokeAll() and invokeAny() methods in the MES and MSES, for any of the submitted tasks that are is rejected by the Work Manager overload policy, the following events will occur:

  • The user-registered ManagedTaskListener's taskSubmitted() method will be called.

  • The user-registered ManagedTaskListener's taskDone() method will be called and the throwableParam will be javax.enterprise.concurrent.AbortedException.

  • The overload reason parameter passed to weblogic.work.Work will be set to the AbortedException.

For the schedule(), scheduleAtFixRate(), scheduleAtFixDelay(), and schedule(Trigger)() methods, if the task is rejected by the Work Manager's overload policy, the following events will occur:

  • The user-registered ManagedTaskListener's taskDone() method will be called, the throwableParam will be javax.enterprise.concurrent.AbortedException.

  • The overload reason parameter passed to weblogic.work.Work will be set to the AbortedException.

  • If the task is periodic, the next run of task will still be scheduled.

Threads Interruption When CMOs Are Shutting Down

When either the MES or MSES is shut down:

  • None of the waiting tasks will be executed.

  • All the running threads will be interrupted. The user should check the Thread.isInterrupted() method and terminate their tasks because WebLogic Server will not force it to terminate.

  • An executor returned Future object will throw the java.util.concurrent.CancellationException() if the Future.get() method is called.

  • User registered ManagedTaskListener's taskAborted() method will be called and paramThrowable will be the CancellationException().

When the MTF is shut down:

  • All threads that it has created using the newThread() method are interrupted. Calls to the isShutdown() method in the ManageableThread interface on these threads return true.

  • All subsequent calls to the newThread() method throw a java.lang.IllegalStateException.

For the ContextService, no thread is interrupted. However:

  • All invocations to any of the proxied interface methods will fail with a java.lang.IllegalStateException.

CMO Constraints for Long-Running Threads

As mentioned above, long-running tasks submitted to MES and MSES and the calling of newThread() method of MTF need to create new threads that will not be managed as a part of the self-tuning thread pool. Because an excessive number of running threads can have a negative affect on server performance and stability, configurations are provided to specify the maximum number of running threads that are created by concurrency utilities API.

Setting Limits for Maximum Concurrent Long Running Requests

The limit of concurrent long-running requests submitted to MES and MSES can be specified in managed object and server levels. All levels of configurations are independent and the maximum of the concurrent long-running requests cannot exceed any of them.

Table 7-4 summarizes the limit of concurrent long-running requests with the max-concurrent-long-running-requests element that can be defined in the deployment descriptors.


Table 7-4 Limit of Concurrent Long-running Requests

Scope Deployment Descriptor Description <max-concurrent-long-running-requests> Element Details

Server

In config.xml:

As the sub-element of <domain><server> or <domain><server-template>

Limit of concurrent Long-running requests specified for that server.

Optional

Range: [0-65534]. When out of range, the default value will be used

Default value: 100

Managed Object

In weblogic-application.xml, weblogic-ejb-jar.xml, or weblogic.xml:

As the sub-element of <managed-executor-service> or <managed-scheduled-executor-service>

in config.xml:

As the sub-element of <managed-executor-service-template> or <managed-scheduled-executor-service-template>

Limit of concurrent long-running requests specified for that MES or MSES.

The same as above with the exception that the default value is 10.


When the specified limit is exceeded, the MES or MSES will take following actions for new long-running tasks submitted to them:

  • The java.util.concurrent.RejectedExecutionException will be thrown when calling the task submission API.

  • If the user registered the task with the ManagedTaskListener, then this listener will not be notified because the submit method failed.

Note that above rule is not applied for the invokeAll() and invokeAny() methods. If any of the tasks submitted by these methods is rejected by the specified limit, the following events will occur:

  • The user-registered ManagedTaskListener's taskSubmitted() method will be called.

  • The user-registered ManagedTaskListener's taskDone() method will be called and the throwableParam will be javax.enterprise.concurrent.AbortedException.

  • Other submitted tasks will not be affected.

  • The method will not throw the RejectedExecutionException.

Example 7-1 demonstrates how the value specified for the max-concurrent-long-running-requests element in the config.xml can affect the maximum number of long-running requests.

Example 7-1 Sample Placements of max-concurrent-long-running-requests in config.xml

<domain>
    <server>
        <name>myserver</server>
        <max-concurrent-long-running-requests>50</max-concurrent-long-running-requests> (place 1)
    </server>
    <max-concurrent-long-running-requests>10</max-concurrent-long-running-requests> (place 2)
    <server-template>
        <name>mytemplate</name>
        <max-concurrent-long-running-requests>50</max-concurrent-long-running-requests> (place 3)
    </server-template>
</domain>
  • place 1 – Affects the MES and MSES defined in the server instance myserver. All the MES and MSES running in that server instance can only create a maximum of 50 long-running-requests in total.

  • place 2 – Only affects MES and MSES defined in the domain. All the MES and MSES running in the domain can create a maximum of 10 long-running-requests in total.

  • place 3 – Affects MES & MSES defined in the server instances that apply to the template mytemplate. All the MES and MSES running in that server instance can only create a maximum of 50 long-running-requests in total.

Example 7-2 demonstrates how the value specified for the max-concurrent-long-running-requests element in the config.xml can affect the maximum number of long-running requests.

Example 7-2 Sample Configurations of max-concurrent-long-running-requests

server1(100)
    |---application1
          |---managed-scheduled-executor-service1(not specified)
          |---module1
                |---managed-executor-service1(20)
                |---managed-scheduled-executor-service2(not specified)
    |---application2

In the following cases, none of the limits are exceeded and the above actions will not be taken:

  • Assume 120 long-running tasks were submitted to managed-executor-service1, 115 of them were finished, 5 of them are being executed, if one more long-running task is submitted to managed-executor-service1, it will be executed because no limit is exceeded.

In the following cases, one of the limits is exceeded and the above actions will be taken:

  • Assume 10 long-running tasks are being executed by managed-scheduled-executor-service1, if one more long-running task is submitted to managed-scheduled-executor-service1, then the limit of managed-scheduled-executor-service1 is exceeded.

  • Assume 10 long-running tasks are being executed by application1, 90 are being executed by application2, if one more long-running task is submitted to application1 or application2, then the limit of server1 is exceeded.

Setting Limits for Maximum Concurrent New Threads

The limit of concurrent new running threads created by calling the newThread() method of the MTF can be specified in a managed object, domain, and server level. All levels of configurations are independent and the maximum of the concurrent new running threads can not exceed any of them.

Note that the meaning of running thread is a thread that has been created by the MTF and which has not finished its run() method.

Table 7-5 summarizes the limit of concurrent new running threads with an element <max-concurrent-new-threads> that can be defined in the deployment descriptors.


Table 7-5 Limit of Concurrent New Running Threads

Scope Deployment Descriptor Description <max-concurrent-long-running-requests> Element Details

Server

In config.xml:

As the sub-element of <domain><server> or <domain><server-template>

Limit of concurrent new running threads specified for that server.

Optional

Range: [0-65534]. When out of range, the default value will be used

Default value: 100

Managed Object

In weblogic-application.xml, weblogic-ejb-jar.xml, or weblogic.xml:

As the sub-element of <managed-executor-service> or <managed-scheduled-executor-service>

in config.xml:

As the sub-element of <managed-executor-service-template> or <managed-scheduled-executor-service-template>

Limit of concurrent new running threads specified for that ManagedThreadFactory

The same as above with the exception that the default value is 10.


When the specified limit is exceeded, calls to the newThread() method of the MTF will return null to be consistent with the ThreadFactory.newThread Javadoc.

To see a sample snippet of using max-concurrent-new-threads, refer to Example 7-2.

Default Java EE CMOs

The Java EE standard specifies that certain default resources be made available to applications, and defines specific JNDI names for these default resources. WebLogic Server makes these names available through the use of logical JNDI names, which map Java EE standard JNDI names to specific WebLogic Server resources.

Default Managed Executor Service

There is a default MES instance for each application. It is automatically bound to the default JNDI name of java:comp/DefaultManagedExecutorService of all the sub-components when deployed.

  • Uses the default Work Manager as the dispatch policy

  • Propagates all the context-info

  • The long-running request limit default is 10

  • The long-running thread priority defaults to normal

You can also use the default MES in applications with the @Resource annotation. For example:

 package com.example;
   public class TestServlet extends HttpServlet {
   @Resource
   private ManagedExecutorService  service;

Overriding the Default MES

The behavior of the default MES can be overridden by:

  • Defining an executor template named DefaultManagedExecutorService in the config.xml. All applications will use this template to create a default MES.

  • Defining a custom managed-executor-service in the weblogic-application.xml, using either deployment descriptors or annotations. This will also override the default MES definition in config.xml in the application. See Custom Managed Executor Service Configuration Elements.

You cannot define a default executor named DefaultManagedExecutorService in the weblogic.xml or weblogic-ejb-jar.xml; doing so will cause the deployment to fail.

Default Managed Scheduled Executor Service

The default MSES instance is similar to the default MES instance, but is automatically bound to the default JNDI name of java:comp/DefaultManagedScheduledExecutorService of all the sub-components when deployed. It has the same default settings and propagates all the context information.

You can also use the default MSES in applications with the @Resource annotation. For example:

 package com.example;
   public class TestServlet extends HttpServlet {
   @Resource
   private ManagedScheduledExecutorService  service;

Overriding the Default MSES

The behavior of the default MSES can be overridden by:

  • Defining a scheduled executor template named DefaultManagedScheduledExecutorService in the config.xml. All applications will use this template to create a default MSES.

  • Defining a custom <managed-scheduled-executor-service> in the weblogic-application.xml, using either deployment descriptors or annotations. This will also override the default MSES definition in config.xml in the application. See Custom Managed Scheduled Executor Service Configuration Elements.

You cannot define a default scheduled executor named DefaultManagedExecutorService in the weblogic.xml or weblogic-ejb-jar.xml; doing so will cause the deployment to fail.

Default Context Service

There is a default context service instance for each application. It is automatically bound to the default JNDI name of java:comp/DefaultContextService of all the sub-components when deployed and propagates all types of supported contexts.

The default Context Service can also be bound to java:comp/env/concurrent/cs under an application component environment (ENC) using the resource-env-ref or @Resource annotation.

Note that the behavior of the default context service cannot be overridden.

Example 7-3 shows how to use the default context service in a webl.xml file using the resource-env-ref element:

Example 7-3 Using the Default Context Service with <resource-env-ref> in a Web App

<!-- web.xml -->
<resource-env-ref>
  <resource-env-ref-name>concurrent/cs</resource-env-ref-name>
  <resource-env-ref-type>javax.enterprise.concurrent.ContextService</resource-env-ref-type>
</resource-env-ref>

Example 7-4 shows how to use the default context service in a servlet with the @Resource annotation:

Example 7-4 Using the Default Context Service with @Resource in a Servlet

// when using @Resource, the following 2 ways are correct.
@Resource(lookup="java:comp/env/concurrent/cs")
// @Resource(name="concurrent/cs")
private ContextService service;

// when using JNDI Naming Context to lookup:
// initialContext.lookup("java:comp/env/concurrent/cs")

Default Managed Thread Factory

There is a default MTF instance for each application. It is automatically bound to the default JNDI name of java:comp/DefaultManagedThreadFactory of all the sub-components when deployed.

  • Propagates all types of supported contexts for new threads

  • The default priority for long-running threads created by newThread() is normal

  • The default limit for running concurrent new threads is 10

You can also use the default MTF in applications with the @Resource annotation. For example:

 package com.example;
   public class TestServlet extends HttpServlet {
   @Resource
   private ManagedThreadFactory  service;

Overriding the Default MTF

The behavior of the default MTF can be overridden by:

  • Defining a thread factory template named DefaultManagedThreadFactory in the config.xml. All applications will use this template to create a default MTF.

  • Defining a custom managed-thread-factory in the weblogic-application.xml, using either deployment descriptors or annotations. This will also override the default MTF definition in config.xml in the application. See Custom Managed Thread Factory Configuration Elements.

You cannot define a default thread factory named DefaultManagedThreadFactory in the weblogic.xml or weblogic-ejb-jar.xml; doing so will cause the deployment to fail.

Customized CMOs in Configuration Files

Customized CMOs can be defined at the application and module level or referenced from an application component environment (ENC) that is bound to JNDI.

Note:

In the current release, a custom Context Service cannot be configured.

Defining CMOs in WebLogic Configuration Files

Customized CMOs can be defined at the application and module level in one of these configuration files:

  • weblogic-application.xml—CMOs specified at the application level can be assigned to that application, or any component of that application.

  • weblogic-ejb-jar.xml or weblogic.xml—CMOs specified at the component level can be assigned to that component.

Binding CMOs to JNDI Under an Application Component Environment

Executor and thread factory CMOs can also be bound to JNDI under an application component environment (ENC) using the resource-env-ref element or the @Resource annotation. The resource-env-ref referencing a CMO can only be defined in web.xml, ejb-jar.xml, or application.xml.

The four ENC namespaces (java:comp, java:module, java:application, and java:global) are supported for resource-env-ref-name and @Resource.

If you bind an executor in an application, AppA, to the java:global JNDI namespace, the executor can be looked up and used by another application, AppB. Tasks submitted by AppB are canceled when AppA or AppB is shutdown

JNDI Binding Using <resource-env-ref>

Example 7-5 demonstrates how to map an MES named MyExecutor to the java:comp/env JNDI namespace.

Example 7-5 Binding an Executor to JNDI Using <resource-env-ref>

   weblogic.xml
   <resource-env-description>
      <resource-env-ref-name>concurrent/MyExecutor</resource-env-ref-name>
      <resource-link>MyExecutor</resource-link>
   </resource-env-description>
 
   web.xml
   <resource-env-ref>
      <resource-env-ref-name>concurrent/MyExecutor</resource-env-ref-name>
      <resource-env-ref-type>javax.enterprise.concurrent.ManagedExecutorService</resource-env-ref-type>
   </resource-env-ref>

In weblogic.xml the resource-link element specifies which executor is being mapped, which in Example 7-5 is named MyExecutor.

Executors defined in weblogic.xml are searched first, followed by weblogic-application.xml, and then the managed-executor-service-template in config.xml to find a executor name attribute that matches the one specified in resource-link.

If the resource-env-description is defined in weblogic-ejb-jar.xml, then weblogic-ejb-jar.xml is searched first, then weblogic-application.xml, and then config.xml.

JNDI Binding Using @Resource

The mapping rules for @Resource annotation are equivalent to those for resource-env-ref, but uses different these naming conventions:

  • resource-env-ref-name is the name attribute value in @Resource.

  • resource-link is equivalent to the mappedName attribute value defined in @Resource.

If @Resource is used under a web component, it is equivalent to define an resource-env-ref under web.xml

If @Resource is used under an EJB component, it is equivalent to define an resource-env-ref under ejb-jar.xml.

The annotation can also be used on class or methods as defined in the Java EE specification.

Example 7-5 using the resource-env-ref definition is equivalent to Example 7-6 using @Resource.

Example 7-6 Binding an Executor to JNDI Using @Resource

   package com.example;
   public class TestServlet extends HttpServlet {
   @Resource(name="concurrent/MyExecutor" mappedName="MyExecutor")
   private ManagedExecutorService  service;

In this example, if the mappedName attribute of @Resource is not specified, then the default executor is used.

If you define both the resource-env-ref and @Resource, and the resource-env-ref-name and name attribute of @Resource are the same, then the resource-env-ref defined executor will be injected into the @Resource field.

You can also use @Resource with a look-up attribute or InitialContext.lookup to find a executor bound by resource-env-ref.

Updated Schemas for Custom CMO Modules

The following WebLogic Server schemas include elements for configuring CMO deployment descriptors:

Example 7-7 shows the CMO-related elements in the weblogic-web-app.xsd.

Example 7-7 CMO Elements in weblogic-web-app.xsd

<xs:complexType name="weblogic-web-appType">
    <xs:sequence>
    <xs:choice minOccurs="0" maxOccurs="unbounded">
      ...
      <!-- added for JSR236 -->
      <xs:element name="managed-executor-service" type="wls:managed-executor-serviceType" minOccurs="0" maxOccurs="unbounded"/>
      <xs:element name="managed-scheduled-executor-service" type="wls:managed-scheduled-executor-serviceType" minOccurs="0" maxOccurs="unbounded"/>
      <xs:element name="managed-thread-factory" type="wls:managed-thread-factoryType" minOccurs="0" maxOccurs="unbounded"/>
      <!-- added end -->
      ...

Updated System Module Beans for CMOs

The following WebLogic Server system module beans include attributes for configuring CMOs in applications and modules:

For more information, see the WebLogic Server System Module MBeans section in the MBean Reference for Oracle WebLogic Server.

Custom Managed Executor Service Configuration Elements

This section defines the configuration elements for a managed executor service.


Table 7-6 Managed Executor Service Configuration Elements

Name Description Required Default Value Range

name

The name of the MES.

An MES with the same name cannot be configured in the same scope. For example, if the same MES name is used in an application or module scope, the deployment of the application will fail.

An MES can have the same name as other types of managed objects, such as a ContextService, in any scope and it will be no relationship between them.

An MES with the same name can only be configured in different scopes if:

  • If there are more than one MES with same name configured in the server template, partition template, or application scope, the partition MES template executor will override the server template, and the application scope MES will override the other two levels.

  • If there is a MES A defined in module scope which name is same with the executor B defined in server template, partition template or application scope. A and B will both exists. Which executor is used is determined by the location referencing the executor.

Yes

n/a

An arbitrary non-empty string.

dispatch-policy

The name of the Work Manager. The rule of which Work Manager should be used is:

  • Search module scope Work Manager first if the ManagedExecutorService is defined in module scope.

  • If not found, search application level.

  • f still not found, the default Work Manger is used. (This behavior is consistent with servlet and EJB's dispatch policy resolving strategy.)

No

Default Work Manager

n/a

max-concurrent-long-running-requests)

Maximum number of concurrent long running tasks.

See Setting Limits for Maximum Concurrent Long Running Requests.

No

10

[0-65534].

When out of range, the default value will be used.

long-running-priority

An integer that specifies the long-running daemon thread's priority. If specified, all long-running threads will be affected.

See Setting Limits for Maximum Concurrent New Threads.

No

Thread.NORM_PRIORITY

1-10

Range between Thread.MIN_PRIORITY and Thread.MAX_PRIORITY. When out of range, the default value will be used.


Deployment Descriptor Examples

Example 7-8 is an example of a custom MES definition in a Web application's weblogic.xml file:

Example 7-8 Using Deployment Descriptor to Define a Custom MES in an Application

<!-- weblogic.xml -->
   <managed-executor-service>
       <name>MyExecutor</name>
       <dispatch-policy>MyWorkManager</dispatch-policy>
       <long-running-priority>10</long-running-priority>
       <max-concurrent-long-running-requests>10</max-concurrent-long-running-requests>
   </managed-executor-service>

Example 7-9 is an example of a custom MES reference in the weblogic.xml descriptor using the <resource-env-ref> element:

Example 7-9 Referencing a Custom MES Using <resource-env-ref> in an Application

weblogic.xml
  <resource-env-description>
    <resource-env-ref-name>concurrent/MyExecutor</resource-env-ref-name
    <resource-link>MyExecutor</resource-link>
  </resource-env-description>

Example 7-10 is an example of a custom MES reference in a webl.xml file using the <resource-env-ref> element:

Example 7-10 Referencing a Custom MES Using <resource-env-ref> in a Web App

web.xml
  <resource-env-ref>
    <resource-env-ref-name>concurrent/MyExecutor</resource-env-ref-name
    <resource-env-ref-type>javax.enterprise.concurrent.ManagedExecutorService</resource-env-ref-type>
  </resource-env-ref>

Example 7-11 is an example of a custom MES reference in a servlet using the @Resource annotation.

Example 7-11 Referencing a Custom MES in a Servlet Using @Resource in a Servlet

package com.example;
public class TestServlet extends HttpServlet {
@Resource(name="concurrent/MyExecutor" mappedName="MyExecutor")
private ManagedExecutorService  service;

Custom Managed Scheduled Executor Service Configuration Elements

This section defines the configuration elements for a managed scheduled executor service.


Table 7-7 Managed Scheduled Executor Service Configuration Elements

Name Description Required Default Value Range

name

The name of the MSES.

For naming convention rules, see Table 7-6.

Yes

n/a

An arbitrary non-empty string.

dispatch-policy

The name of the Work Manager.

For Work Manager usage rules, see Table 7-6.

No

Default Work Manager

n/a

max-concurrent-long-running-requests

Maximum number of concurrent long running tasks.

See Setting Limits for Maximum Concurrent Long Running Requests.

No

10

[0-65534].

When out of range, the default value is used.

long-running-priority

An integer that specifies the long-running daemon thread's priority. If specified, all long-running threads will be affected.

See Setting Limits for Maximum Concurrent New Threads.

No

5 Thread.NORM_PRIORITY

1-1

Range between Thread.MIN_PRIORITY and Thread.MAX_PRIORITY. When out of range, the default value is used.


ScheduledFuture.get() Method

The ScheduledFuture.get() method will block until the latest run of the task finishes. For example, if the Trigger method requires the task being scheduled to run two times (i.e., Trigger.getNextRunTime returns null on the third call), and the first run of the task is finished at time A, the second run of the task is finished at time B, then:

  • If Future.get() is called before time A, it will wait for the first run to finish and return the first run result. If it is called after time A and before time B, it will wait to the second run finish and return the second run's result.

  • If Future.get() is called after time B, it will immediately return the second run result. Also, if the first run fails and throws a exception, then the first Futhur.get call will throw that exception and the second run will still be scheduled (this is different with scheduleAtFixRate). If the Trigger.skipRun returns true on the first run, then the first Future.get call will throw a SkipException.

Deployment Descriptor Examples

Example 7-12 is an example of a custom MSES definition in a Web application's weblogic.xml file:

Example 7-12 Using Deployment Descriptor to Define a Custom MSES in an Application

<!-- weblogic.xml -->
   <managed-scheduled-executor-service>
       <name>MyScheduledExecutor</name>
       <dispatch-policy>MyExecutor</dispatch-policy>
   </managed-scheduled-executor-service>

Custom Managed Thread Factory Configuration Elements

This section defines the configuration elements for a managed thread factory.


Table 7-8 Managed Thread Factory Configuration Elements

Name Description Required Default Value Range

name

The name of the MTF.

For naming convention rules, see Table 7-6.

Yes

n/a

An arbitrary non-empty string.

priority

The priority to assign to the thread. (The higher the number, the higher the priority.)

See Setting Limits for Maximum Concurrent New Threads.

No

5 Thread.NORM_PRIORITY

1-10 Range between Thread.MIN_PRIORITY and Thread.MAX_PRIORITY. When out of range, the default value is used.

max-concurrent-new-threads

The maximum number of threads created by the MTF and are still executing the run() method of the tasks.

See Setting Limits for Maximum Concurrent New Threads.

No

10

[0-65534]

When out of range, the default value is used.


Contexts of Threads Created by MTF

According to JSR236, the Managed Thread Factory is different from the other managed objects because when the thread is started using the Thread.start() method, the runnable that is executed will run with the context of the application component instance that created the ManagedThreadFactory instance. Therefore, the context of the runnable depends on the application component that created the MTF instance.

In WebLogic Server, new MTF instances are created when an application or a component is started, as follows. (A component means a web module or an EJB.)

  1. A default MTF is created by that component.

  2. If there is @Resource annotation to get an MTF, an MTF instance is created by that component.

  3. If there is a <resource-env-ref> defined in web.xml/ejb-jar.xml, and there is also a corresponding <resource-env-description> defined in weblogic.xml/weblogic-ejb-jar.xml with a <resource-link> for an MTF, then an MTF instance is created by that component.

  4. If there is a <resource-env-ref> defined in application.xml, and there is also a corresponding <resource-env-description> defined in weblogic-application.xml with a <resource-link> for an MTF, then an MTF instance is created by that application.

When an MTF is created by a component in the case of items 1, 2, and 3 listed above, the Runnable runs with the context of that component, as follows:

  • ClassLoader: the class loader of that component.

  • JNDI: The JNDI tree of that component that contains java:app, java:module, and java:comp.

  • Security: Fixed to be the anonymous subject because there is no component-specific subject.

  • WorkArea: Fixed to be an empty WorkContextMap because there is no component-specific WorkContextMap.

When an MTF is created by an application in the case of 4, the Runnable run with the context of that application as follows:

  • ClassLoader: The class loader of that application.

  • JNDI: The JNDI tree of that component that contains java:app but without java:module and java:comp.

  • Security: Fixed to be the anonymous subject because there is no application-specific subject.

  • WorkArea: Fixed to be an empty WorkContextMap because there is no application-specific WorkContextMap.

Deployment Descriptor Examples

Example 7-13 is an example of a custom MTF definition in a Web application's weblogic.xml file:

Example 7-13 Using Deployment Descriptors to Define a Custom MTF in an Application

<!-- weblogic.xml -->
   <managed-thread-factory>
       <name>factory1</name>
       <priority>3</priority>
       <max-concurrent-new-threads>20</max-concurrent-new-threads>
   </managed-executor-service>

Example 7-9 is an example of a custom MTF reference in a Web application's weblogic.xml file:

Example 7-14 Referencing a Custom MTF Using <resource-env-ref> in an Application

weblogic.xml
  <resource-env-description>
    <resource-env-ref-name>ref-factory1</resource-env-ref-name
    <resource-link>factory1</resource-link>
  </resource-env-description>

Example 7-10 is an example of a custom MTF reference in a Web application's weblogic.xml file:

Example 7-15 Referencing a Custom MTF Using <resource-env-ref> in a Web App

web.xml
  <resource-env-ref>
    <resource-env-ref-name>ref-factory1</resource-env-ref-name
    <resource-env-ref-type>javax.enterprise.concurrent.ManagedThreadFactory</resource-env-ref-type>
  </resource-env-ref>

Example 7-11 is an example of a custom MTF reference in a servlet using the @Resource annotation:

Example 7-16 Referencing a Custom MTF Using @Resource in a Servlet

package com.example;
public class TestServlet extends HttpServlet {
@Resource(lookup="java:comp/env/ref-factory1")
private ManagedThreadFactory factory;

Transaction Management for CMOs

This section explains how transactions are managed by WebLogic Server for CMOs.

Transaction Management for MES and MSES

When using an MES, transactions are managed as follows:

  • There are no transaction running in the Work Manager thread before the task is begun.

  • The UserTransaction.getStatus() method is always Status.STATUS_NO_TRANSACTION unless the Transaction API is used to start a new transaction.

  • User should always finish its transaction in user tasks; otherwise, the transaction will be rolled backed.

Therefore ManagedTask.TRANSACTION and related attributes will be ignored.

Transaction Management for Context Service

By default, or by setting the value of execution property ManagedTask.TRANSACTION to ManagedTask.SUSPEND:

  • Any transaction that is currently active on the thread will be suspended.

  • A javax.transaction.UserTransaction accessible in the local JNDI namespace as java:comp/UserTransaction will be available so contextual proxy object may begin, commit, and roll back a transaction.

  • If a transaction begun by a contextual proxy object is not completed before the method ends, a WARNING log will be output, and the transaction will be rolled back.

  • The original transaction, if any was active on the thread, will be resumed when the task or contextual proxy object method returns.

By setting the value of execution property ManagedTask.TRANSACTION to ManagedTask.USE_TRANSACTION_OF_EXECUTION_THREAD:

  • The transaction will managed by the execution thread and the task themselves, so that any transaction that is currently active on the thread will not be suspended when contextual proxy object method begins, and will not be resumed when contextual proxy object method returns.

  • If there is a currently active transaction on the thread, any resources used by the contextual proxy object will be enlisted to that transaction.

  • If a transaction began by the contextual proxy object is not completed before the method ends, WebLogic Server will do nothing about it because there is the possibility that the transaction is completed by another method of the contextual proxy object.

Transaction Management for MTF

When using the MTF, transactions are managed as follows:

  • The task runs without an explicit transaction (they do not enlist in the application component's transaction), so the UserTransaction.getStatus() method always returns Status.STATUS_NO_TRANSACTION, unless a new transaction is started in the task.

  • If the transaction is not completed before the task method ends, a WARNING log will be output, the transaction will be rolled back.

Global CMO Templates

In addition to the JSR236 default CMOs, you can also define global CMOs as templates in the domain's configuration by using the WebLogic Server Administration Console and configuration MBeans. CMOs specified in config.xml can be assigned to any application, or application component, in the domain.

Note:

Partitioned domains for multi-tenancy are only available in WebLogic Server Premium Edition. For more information, see LINK TO INTRO TO WEBLOGIC SERVER MT.

Note:

You should normally use the Administration Console to configure WebLogic Server's manageable objects and services and allow WebLogic Server to maintain the config.xml file.

You can define three types of CMO templates in a domain:

  • Managed Executor Service Template

  • Managed Scheduled Executor Service Template

  • Managed Thread Factory Template

For example, if you define a managed-executor-service-template, a unique MES instance is created for each application deployed in the domain.

Configuring CMO Templates using the Administration Console

CMO templates can be configured globally in the domain's configuration using the WebLogic Server Administration Console.

  1. In the Domain Structure tree, expand Environment and click Concurrent Templates.
  2. Click New and choose one of the following template options:
    • Managed Executor Service Template

    • Managed Scheduled Executor Service Template

    • Managed Thread Factory Template

  3. On the Create New Template page, enter the template properties as required. The properties vary depending on which type of concurrent template you are creating.
  4. Click Next.
  5. Select whether to target the concurrent template to a specific WebLogic Server instance or to a WebLogic Server cluster.

    Only applications that have been deployed to the selected servers or clusters can use this concurrent template.

  6. Click Finish. The Summary of Concurrent Templates page displays and the new concurrent template is listed.
  7. Repeat these steps to create other concurrent templates as necessary.

For instructions about using the WebLogic Server Administration Console to manage a WebLogic Server domain, see the Oracle WebLogic Server Administration Console Online Help.

Using MBeans to Configure CMO Templates

CMO templates can be configured using the following configuration MBeans under the DomainMBean.

For more information, see the Domain Configuration MBeans section in the MBean Reference for Oracle WebLogic Server.

Configuring Concurrent Constraints

Constraints can also be defined globally in the domain's configuration using the WebLogic Server Administration Console and configuration MBeans. Concurrent constraints specified in config.xml can be assigned to any application, or application component, in the domain.

Using the Administration Console to Configure Concurrent Constraints

Concurrent constraints can be configured in the domain configuration, in specified server instances, and in server templates for dynamic clusters, using the Administration Console.

Domain-level Concurrent Constraints

To configure concurrent constraints for a domain:

  1. In the Domain Structure tree, select the domain name at the top of the tree.
  2. Select the Configuration > Concurrency tab.
  3. On the Concurrency page, specify a value for any or all of the available options:
  4. Click Save.

Server-level Concurrent Constraints

To configure concurrent constraints for specific server instances in a domain:

  1. In the Domain Structure tree, expand Environment and click Servers.
  2. In the Summary of Servers table, select a server instance.
  3. On the Concurrency page, specify a value for any or all of the available options:
  4. Click Save.

Dynamic Cluster-level Concurrent Constraints

To configure concurrent constraints for server templates in a dynamic cluster:

  1. In the Domain Structure tree, expand Environment, expand Clusters, and click Server Templates.
  2. In the Summary of Server Templates table, select a server template instance.
  3. Select the Configuration > Concurrency tab.
  4. On the Concurrency page, specify a value for any or all of the available options:
  5. Click Save.

Using MBeans to Configure Concurrent Constraints

Concurrent constraints can be configured globally in the domain's configuration, in specified server instances, and in server templates for dynamic clusters using the following methods under the DomainMBean, ServerMBean, and ServerTemplateMBean:

For more information about using WebLogic Server MBeans, see Accessing WebLogic Server MBeans with JMX in Developing Custom Management Utilities Using JMX for Oracle WebLogic Server.

Querying CMOs

Global CMOs can be queried using these administrative tools:

Using the Administration Console to Monitor CMO Threads

CMOs can be monitored using the Administration Console.

To monitor the threads created by CMOs in a server instance:

  1. In the Domain Structure tree, expand Environment and click Servers.
  2. In the Summary of Servers table, select a server template instance.
  3. On the Settings page, select the Monitoring > Concurrency tab.

    The tab displays the statistics for CMO threads created in the global runtime.

Monitor JSR236 CMOs for All Deployed Applications and Modules

To monitor the statistics for all JSR236 CMOs in a domain:

  1. In the Domain Structure tree, click Deployments.

  2. In the Summary of Deployments page, select the Monitoring > Concurrency tab.

    The tab displays the statistics for all the CMOs of all the deployed applications and modules in the domain by calling the relevant runtime MBeans.

Monitor JSR236 CMOs for a Deployed EAR or Module

To monitor the statistics for all JSR236 CMOs in a domain:

  1. In the Domain Structure tree, click Deployments.

  2. In the Summary of Deployments page, select the EAR or module that you want to monitor.

  3. On the Settings page, select the Monitoring > Concurrency tab.

    Depending on what type of application or module was selected, the tab displays the statistics from the corresponding runtime MBean:

    • EAR Application – displays statistics for all the concurrent objects of that application (by calling ApplicationRuntimeMBean).

    • Web app or EJB module within an EAR – Displays statistics for all the concurrent objects of that module (by calling ComponentRuntimeMBean).

    • Standalone Web app or EJB module – displays statistics for all the concurrent objects of that Web app or module (by calling ApplicationRuntimeMBean and ComponentRuntimeMBean).

Using MBeans to Monitor CMOs

CMOs can be monitored using the following runtime MBeans under the DomainMBean.

  • ManagedExecutorServiceRuntimeMBean

    The ManagedExecutorServiceRuntimeMBean can be accessed from the following MBean attributes:

    • ApplicationRuntimeMBean.ManagedExecutorServiceRuntimes – Provides statistics for all the Managed Executor Services of that application.

    • ComponentRuntimeMBean.ManagedExecutorServiceRuntimes – Provides statistics for all the Managed Executor Services of that module.

    See the ManagedExecutorServiceTemplateMBean in the MBean Reference for Oracle WebLogic Server

  • ManagedScheduledExecutorServiceRuntimeMBean

    The ManagedScheduledExecutorServiceRuntimeMBean can be accessed from the following MBean attributes:

    • ApplicationRuntimeMBean.ManagedScheduledExecutorServiceRuntimes – Provides statistics for all the Managed Scheduled Executor Services of that application.

    • ComponentRuntimeMBean.ManagedScheduledExecutorServiceRuntimes – Provides statistics for all the Managed Scheduled Executor Services of that module.

    See the ManagedScheduledExecutorServiceRuntimeMBean in the MBean Reference for Oracle WebLogic Server

  • ManagedThreadFactoryRuntimeMBean

    The ManagedThreadFactoryRuntimeMBean can be accessed from the following MBean attributes:

    • ApplicationRuntimeMBean.ManagedThreadFactoryRuntimes – Provides statistics for all the Managed Thread Factories of that application.

    • ComponentRuntimeMBean.ManagedThreadFactoryRuntimes – Provides statistics for all the Managed Thread Factories of that module.

    See the ManagedThreadFactoryRuntimeMBean in the MBean Reference for Oracle WebLogic Server

For more information about using WebLogic Server MBeans, see Accessing WebLogic Server MBeans with JMX in Developing Custom Management Utilities Using JMX for Oracle WebLogic Server.

Using MBeans to Monitor Concurrent Constraints

A server's concurrent constraints can be monitored using the ConcurrentManagedObjectsRuntimeMBean, which can be accessed from the following MBean attribute:

  • ServerRuntimeMBean.ConcurrentManagedObjectsRuntime – Provides statistics for threads created by concurrent managed objects of global runtime.

See the ConcurrentManagedObjectsRuntimeMBean in the MBean Reference for Oracle WebLogic Server

For more information about using WebLogic Server MBeans, see Accessing WebLogic Server MBeans with JMX in Developing Custom Management Utilities Using JMX for Oracle WebLogic Server.