Tuesday Jan 12, 2016

ZDT Technical Topic: How are Those Sessions Kept Alive Anyway?

By now you have probably read documentation or previous blog posts about how Zero Downtime Patching provides a convenient automated method of updating a WebLogic Domain in a rolling fashion.  By automating the process, Zero Downtime Patching greatly saves time and eliminates the potential human errors from the repetitive course of procedure. In addition to that there is also some special features around replicated HTTP sessions that make sure end users do not lose their session at any point during the rollout process. Lets explore the technical details around maintaining session state during Zero Downtime Patching.


One of the key aspects of WLS replicated session persistence contract is that the session may be maintained within the cluster even in the rare situation where a server crashes. However, the session persistence contract cannot guarantee sessions will be maintained when more than a single server goes down in a short time period. This is because the session has a single copy replicated to some secondary server within the cluster. The session is only replicated when the client makes a request to update the session so the client’s cookie can store a reference to the secondary server. Thus, if the primary server were to go down and then the secondary server were to go down before the session could be updated by a subsequent client request then the session would be lost. The rolling nature of Zero Downtime Patching fits this pattern, and thus must take extra care to avoid losing sessions. Administrators may have already observed that it is very easy to lose sessions by restarting one server at a time through the cluster.


Before we go into technical details on how Zero Downtime Patching prevents the issue of losing sessions, it is important to note that the entire methodology relies on Oracle Traffic Director for load balancing, dynamic discovery, health checks, and session failover handling. In addition to this setup, 3 key features were utilized by Zero Downtime Patching directly to prevent the loss of sessions:

Session Handling Overview


1. Preemptive Session Replication - Session data is preemptively propagated to another server in the cluster during graceful shutdown when necessary.  To get even more detailed on this, lets examine the scenario where the ZDT rollout has shutdown the server holding the HTTP Session, and the next step is to shutdown the server holding the replica. In that case, WebLogic can detect during shutdown that the session will be lost as there is no backup copy within the cluster. So the ZDT rollout can ensure that WebLogic Server replicates that session to another server within the cluster.

The illustration below shows the problematic scenario where the server,  s1, holding the primary copy of the session is shutdown followed by the shutdown of the server, s2, holding the secondary or replica copy.  The ZDT Orchestration signals that s2 should preemptively replicate any single session copies before shutting down.  Thus there is always a copy available within the cluster.  

Preemptive Session Replication on Shutdown


2. Session State Query Protocol - Due to the way that WebLogicServer relies on the association of an HTTP Session with a primary server and a secondary server, it is not sufficient to simply have the session somewhere in the cluster.  There is also a need to be able to find the session when the client request lands on an arbitrary server within the cluster. The ZDT rollout enables the ability for WebLogicServers to query other servers in the cluster for specific sessions if they don’t have their own copy.

Session Fetching via Session State Protocol Query

The diagram above shows that an incoming request to a server without the session can trigger a query and once the session is found within the cluster it can be fetched so that the request can be served on the server, "s4". 


3. Orphaned Session Cleanup - Once we combine the ability to preemptive replicate session instances, and the ability to fetch sessions from within the cluster, we must also take a more active approach to cleanup instances that are fetched.  Historically, WebLogic Server hasn’t had to worry much about orphaned sessions. Front end load balancers and web servers have been required to honor the session’s server affinity. And in the rare case that a request would land on a server that did not contain the primary or secondary, the session would be fetched from the primary server or secondary server and then the orphaned copy would be forgotten to be cleaned up upon timeout or other regular intervals. It was assumed that because the pointer to the session changed, that the actual stored reference would never be used again. However, the ZDT rollout repeatedly presents the scenario where a session must be found within the cluster and fetched from the server that holds the session. Not only can the number of session instances proliferate - all with various versions of the same session - the cluster is now queried for the copy and we must not find any stale copies - only the current replica of the session.

Orphaned Session Cleanup

The above illustration shows the cleanup action after s4 has fetched the session data to serve the incoming request.  It launches the cleanup request to s3 to ensure no stale data is left within the cluster.


Summary:

Now during ZDT Patching we can shutdown server1, and expect that any lone session copies will be propagated to server2 without the clients knowledge. When the client does send another request, WLS will be able to handle that request and query the cluster to find the session data. The data will be fetched and used on the server handling the request. The orphaned copy will be cleaned up and the server handling the request will go through the process of choosing its preferred Secondary server to store the replica.



For more information about Zero Downtime Patching, view the documentation

(http://docs.oracle.com/middleware/1221/wls/WLZDT/configuring_patching.htm#WLZDT166)


References

https://docs.oracle.com/cd/E24329_01/web.1211/e24425/failover.htm#CLUST205

Friday Jan 08, 2016

ZDT Rollouts and Singletons

WebLogic Server offers messaging, transaction and other system services to facilitate building enterprise grade applications. Typically, services can be either clustered or singleton. Clustered services are deployed identically to each server in a cluster to provide increased scalability and reliability. The session state of one clustered server is replicated on another server in the cluster. In contrast, singleton services run on only one server in a cluster at any given point of time so as to offer specific quality of service (QOS) but most importantly to preserve data consistency. Singleton services can be JMS-related, JTA-related or user-defined. In highly available (HA) environments, it is important for all services to be up and running even during patch upgrades.

The new WebLogic Zero Downtime Patching (a.k.a ZDT patching) feature introduces a fully automated rolling upgrade solution to perform upgrades such that deployed applications continue to function and are available for end users even during the upgrade process. ZDT patching supports rolling out Oracle Home, Java Home and also updating applications. Check out these blogs or view the documentation for more information on ZDT.

[Read More]

Tuesday Dec 15, 2015

Even Applications can be Updated with ZDT Patching

Zero Downtime Patching enables a convenient method of updating production applications on WebLogic Server without incurring any application downtime or loss of session data for your end-users.  This new feature may be especially useful for users who want to update multiple applications at the same time, or for those who cannot take advantage of the Production Redeployment feature due to various limitations or restrictions. Now there is a convenient alternative to complex application patching methods.

This rollout is based on the process and mechanism for automating rollouts across a domain while allowing applications to continue to service requests. In addition to the reliable automation, the Zero Downtime Patching feature also combines Oracle Traffic Director (OTD) load balancer and WebLogic Server to provide some advanced techniques for preserving active sessions and even handling incompatible session state during the patching process.

To rollout an application update, follow these 3 simple steps.

1. Produce a copy of the updated the application(s), test and verify. Note the administrator is responsible for making sure that the updated application sources are distributed to the appropriate nodes.  For stage mode, the updated application source needs to be available on the file system for the AdminServer to distribute the application source.  For no stage and external stage mode, the updated application source needs to be available on the file system for each node.

2. Create a JSON formatted file with the details of any applications that need to be updated during the rollout.


{"applications":[
{
"applicationName":"ScrabbleStage",
"patchedLocation":"/scratch/wlsconfg/Domains/Domain1221/applications/ScrabbleStagev2.war",
"backupLocation": "/scratch/wlsconfg/Domains/Domain1221/applications/ScrabbleStagev1.war"
},
{
"applicationName":"ScrabbleNoStage",
"patchedLocation":"/scratch/wlsconfg/Domains/Domain1221/applications/ScrabbleNoStagev2.war",
"backupLocation":"/scratch/wlsconfg/Domains/Domain1221/applications/ScrabbleNoStagev1.war"
},
{
"applicationName":"ScrabbleExternalStage",
"patchedLocation":"/scratch/wlsconfg/Domains/Domain1221/applications/ScrabbleExternalStagev2.war",
"backupLocation":"/scratch/wlsconfg/Domains/Domain1221/applications/ScrabbleExternalStagev1.war"
}
]}

3. Simply run the Application rollout using a WLST command like this one:

rolloutApplications(“Cluster1”, “/pathTo/applicationRolloutProperties”)

The Admin Server will start the rollout that coordinates the rolling restart of each node in the cluster named “Cluster1”. While the servers are shutdown, the original application source is moved to the specified backup location, and the new application source is copied into place.  Each server in turn is then started in admin mode.  While the server is in admin mode, the application redeploy command is called for that specific server, causing it to reload the new source.  Then the server is resumed to its original running state and is serving the updated application.

For more information about updating Applications with Zero Downtime Patching view the documentation.

Monday Dec 14, 2015

WLS 12.2.1 launch - Servlet 3.1 new features

[Read More]

Wednesday Dec 09, 2015

New EJB 3.2 feature - Modernized JCA-based Message-Driven Bean

WebLogic Server 12.2.1 is a fully compatible implementation of Java EE 7 specification. One of the big improvements in EJB container in this release of WebLogic Server is that, a message-driven bean is able to implement a listener interface with no methods. When such a no-methods listener interface is used, all non-static public methods of the bean class (and of the bean class's super classes except java.lang.Object) are exposed as message listener methods.

[Read More]

Monday Dec 07, 2015

Multi-Tenancy Samples

In order to make it easier to understand all aspects of Multi-tenancy in WebLogic Server 12.2.1, MedRec can support running in a Multi-tenancy environment to be used as a demonstration vehicle.

What’s MedRec

Avitek Medical Records (or MedRec) is a WebLogic Server sample application suite that demonstrates all aspects of the Java Platform, Enterprise Edition (Java EE). MedRec is designed as an educational tool for all levels of Java EE developers. It showcases the use of each Java EE component, and illustrates best-practice design patterns for component interaction and client development. MedRec also illustrates best practices for developing and deploying applications with WebLogic Server.

Please choose 'Complete with Examples' when you install WebLogic server whilst going to the step of 'Installation Type'. The codes, binaries and documentations of MedRec will be located at ‘$MW_HOME/wlserver/samples/server/medrec’ directory. Otherwise samples of WebLogic Server will be overleaped.

There are two non-OOTB Multi-tenancy samples. You need to run Ant commands provided to stage WebLogic domains.

Single Server Multi-tenancy MedRec

Overview

It’s a SAAS sample that is all focusing on the Multi-tenancy features themselves, without cluster, extra managed servers, all virtual targets only target to admin server.


Multi-tenancy Demonstration

There are 2 tenants named bayland and valley, and valley has 2 partitions(one tenant can have multiple partitions). In this sample, it’s demonstrating various Multi-tenancy features following. If you have any questions about a certain feature, you'd refer to the relevant blogs or documentations.


Resource Group Template

All resources including applications, JMS, file store, mail session, JDBC system resource are deployed onto a resource group template.


  • Applications


  • Other resources


Resource Overriding

Databases are supposed to be isolated among partitions. At resource group template, the JDBC system resource is a mere template with name, driver, JNDI lookup name. The real URL, username, password of datasource are set at the resource overriding in Partition scope.


Virtual Target

Each partition, exactly each partition resource group deriving from forementioned MedRec resource group template has it own virtual target. The 2 virtual target of valley share the same host names within different URI prefixes.


We can see three virtual targets, one per one partition. Web container is aware of which application is accessed to according to the host name plus URI prefix. For example, in this sample, medrec.ear is deployed at all partitions. Yet how to access the web module of medrec.ear on bayland? The URL would be 'http://hostname:port/bayland/medrec'. '/bayland' is the uri prefix. 'medrec' is the root context name of webapp.


Security Realm

Each tenant is supposed to have its own security realm with isolated users. MedRec has an use case of Servlet access control and authentication that demonstrates the scenario.


Resource Consumption Management.

Bayland is deemed as a VIP customer of this sample. So it has more quota of CPU, memory heap, thread work, etc.


Trigger will slow down or shut down the partition if the usage is up to the specified value.


Partition Work Manager

Partition Work Managers define a set of policies that limit the usage of threads by Work Managers in partitions only. They do not apply to the domain.


Deployment Plan

Then deployment plan file can be used in partition scope. The sample utilises this mechanism to change the appearance of the web pages on valley tenant including photos and background colour. That means you can let your application different from each other of different partition even though of one resource group template.

Installation

Prior to running setup script, you need to do a couple of preparation. Setting sample environment, editing etc/hosts file, customising the properties of admin server, host, port etc. After that, one ant command will stage all content of the SAAS sample.

  1. Setting environment.

    cd $MW_HOME/wlserver/samples/server
    . ./setExamplesEnv.sh
  1. Network address mapping. Please open /etc/hosts file and add following lines:

    127.0.0.1 www.baylandurgentcare.com
    127.0.0.1 www.valleyhealth.com
  2. Customizing admin server properties.
    update 5 properties in $MW_HOME/wlserver/samples/server/medrec/weblogic.properties. Please use weblogic as the username of the admin server.

    admin.server.name=adminServer
    admin.server.host=localhost
    admin.server.port=7005
    admin.server.username=weblogic
    admin.server.password=XXXXXX
  3. Running setup script

    cd $MW_HOME/wlserver/samples/server/medrec
    ant mt.single.server.sample

Webapp URLs

You can access MedRec via following URLs according to the server port you set. For example, you set admin.server.port = 7001.

Coherence Cluster Multi-tenancy MedRec

Overview

The second SAAS sample. Beyond the simple one, coherence cache, dynamic cluster, Oracle PDB are involved. In some extent, it’s a real usage of MT in practice.


Look at this diagram above, it also has 2 tenants but a partition per tenant. Bayland is the blue one, valley the green one. There are 2 resource group templates named app RGT and cache RGT instead of one. App RGT is similar to the resource group template of the first MT sample including all resources of MedRec. In order to enable coherence cache, a GAR archive is packaged into an application of medrec.ear. And the identical GAR is also deployed into the second cache resource group template. Both of the partitions have 2 resource groups app and cache deriving from the app and cache resource group templates respectively. Each resource group targets to different virtual target. So here has 4 virtual targets. 2 app virtual targets target to a storage disabled dynamic cluster app cluster with 2 managed servers. The applications and other resources run on this app cluster. In contrast, 2 cache virtual targets target to another dynamic cluster named cache cluster with 2 managed servers but storage enable. The GAR of cache resource group runs on the cache cluster.


Coherence Scenario

MedRec has 2 key archives medrec.ear and physician.ear. Physician archive is set to a web service(JAX-RS and JAX-WS) client application. And there aren't any JPA stuff in physician.ear all of which are in server side.  So leveraging Coherence Cache here can avoid frequent web service invocations and JDBC invocations in business services of web service server side.

Method Invocation Cache

This cache is one partitioned tenant cache. Most of business services of physician scenarios are annotated method invocation cache interceptor. First check data whether it has stored in cache. If data isn't cached, gets data through web service. Then stores return data into method cache. After that, following invocations with same values of parameter will fetch data from cache directly.

When is the data removed from the method cache? For examples, physician can look a patient's record summary which is cached after first getting the data. And physician creates a new record for this patient. At present, the record summary in the cache has already been inaccurate. So the dirty data should be cleaned. In this case, after success of creating record, the business service will fire an update event to remove the old data.

Actually, Method invocation cache has 3 different types. MedRec can be aware of the WLS environment and activate the relevant cache.

For example, physician login, when you first login as physician at bayland app server 1, the app_cluster-1.log should be printed liking following logs:

Method Invocation Coherence Cache is available.
Checking method XXXX invocation cache...
Not find the result.
Caching the result in method XXXX invocation cache....
Added result to cache
Method: XXXXX
Parameters: XXXX
Result: XXXXX

Logout and change to bayland server 2 login again, the app_cluster-2.log should like these:

Checking method XXXX invocation cache...
Found result in cache
Method: XXXXX
Parameters: XXXX
Result: XXXXX

Shared Cache

This cache is one partitioned shared cache that means bayland and valley can share it. It's still the creating record user-case. Physician can create prescriptions for the new record. Choosing drug uses a drug information list from database of server side. The list is a stable invariable data so that can be shared with both Partitions. So the drug information list is stored in this cache.

Open creating record page on browser at bayland server 1, the app_cluster-1.log should like this:

Drug info list is not stored in shared cache.
Fetch list from server end point.
Store drug info list into shared cache.

Then do the same thing at valley server 2, the app_cluster-2.log should like this:

Drug info list has already stored in shared cache.

That means the it is a shared cache over Partitions.

Installation

The installation and usage are similar to the first MT sample. Beyond the first one, the first sample adopts derby as database, the second adopts Oracle database. You need to prepare 2 Oracle PDBs and customize the file of db properties.

  1. Setting environment.

    cd $MW_HOME/wlserver/samples/server
    . ./setExamplesEnv.sh
  2. Update 5 properties in $MW_HOME/wlserver/samples/server/medrec/install/mt-coherence-cluster/configure.properties according with PDBs. E.g.:

    # Partition 1
    dbURL1      = jdbc:oracle:thin:XXXXXXXX:1521/pdb1
    dbUser1     = pdb1
    dbPassword1 = XXXXXX
    # Partition 2
    dbURL2      = jdbc:oracle:thin:XXXXXXXX:1521/pdb2
    dbUser2     = pdb2
    dbPassword2 = XXXXXX
  3. Network address mapping. Please open /etc/hosts file and add following lines:

    127.0.0.1 bayland.weblogicmt.com
    127.0.0.1 valley.weblogicmt.com
  4. Customizing admin server properties.
    update 5 properties in $MW_HOME/wlserver/samples/server/medrec/weblogic.properties. Please use weblogic as the username of admin server.

    admin.server.name=adminServer
    admin.server.host=localhost
    admin.server.port=7003 (Please don’t use 2105, 7021, 7022, 7051, 7052 which will be used as servers’ listening ports)
    admin.server.username=weblogic
    admin.server.password=XXXXXX
  5. Running setup script

    cd $MW_HOME/wlserver/samples/server/medrec
    ant mt.coherence.cluster.sample

Webapp URLs

After success, please access following URLs to experience MedRec:

Wednesday Nov 25, 2015

Multi-Tenancy EJB

Multi-Tenancy EJB

Benefit from the Multi-Tenancy support of WLS 12.2.1, EJB container gains a lot of enhancements. Application and resource "multiplication" allows for EJB container to provide MT features while remaining largely partition unaware. Separate application copies also brings more isolation, such as distinct Remote objects, beans pools, caches, module class loader instances etc. Below names a few of the new features you can leverage for EJB applications.

1. JNDI

  • Server naming nodes will be partition aware.
  • Applications deployed to partitions will have their EJB client views exposed in the corresponding partition's JNDI namespace. 

2. Security

  • Security implementation now allows multiple active realms, including support for per-partition security realm.
  • Role based access control, and credential mapping for applications deployed to partition will use the partition's configured realm.

3. Runtime Metrics and Monitoring

  • New ApplicationRuntimeMBean instance with the PartitionName attribute populated, will get created for every application deployed to a partition.
  • EJB container exposed Runtime MBean sub-tree will be rooted by the ApplicationRuntimeMBean instance.

4. EJB Timer service

  • Persistent local timers rely on the store component. Partitioned custom file stores provide the required isolation of tenant data.
  • Clustered timers under the hood use Job scheduler, which is also providing isolation.

5. JTA configuration at Partition Level

  • JTA timeout can be configured at partition level, in addition to domain level and EJB component level.
  • Timeout value in EJB component level takes precedence over the other two.
  • Support dynamic update via deployment plan.

6. WebLogic Store

  • Persistent local timers rely on the store component. Partitioned custom file stores provide the required isolation of tenant data. 

7. Throttling Thread Resource usage

  • Work Managers with constraints can be defined at global runtime level, and application instances in partitions can refer to these shared WMs to throttle thread usage across partitions esp. for non interactive use cases - batch, async, message driven bean invocations ...

8. Data Sources for Java Persistence API users

  • Persistence Units that use data sources defined as system resources in the Resource Group Template will be able to take advantage of the PartitionDataSourceInfoMBean based overrides.
  • Use cases requiring advanced customization can use the new deployment plan support being added for system resource re-configuration.
  • Persistence Units that use application packaged data source modules can use the current deployment plan support to have the copies in different partitions, point to the appropriate PDBs.


A sample EJB application leveraging Multi-Tenancy

Now we're going through a simple setup of an EJB application on MT environment to demonstrate the usage of some of these features.

The EJB application archive is named sampleEJB.jar, it includes a stateful session bean which interacts with database by JPA API. We want the application to be deployed to 2 separate partitions, each of which points to a database instance of its own, so they can work independently.

1.  Create Virtual Targets

The first step is to create 2 virtual targets for the 2 partitions respectively, which use different URI prefixes /partition1 and /partition2 respectively as showed below.

2.  Create Resource Group Template

Now we create a Resource Group Template named myRGT.  Resource Group Template is a new concept introduced by WLS 12.2.1, to which you can deploy your applications and different resources you need. This is very helpful when your application setup is complicated, because you don't want to repeat the same thing for multiple times on different partitions.


3.  Deploy application and data source

Now we can deploy the application and define the data source as below. Please pay attention that the application and the data source are all defined in myRGT scope.

4.  Create Partitions

Now everything is ready, it's time to create partitions. As the following image shows, we can apply the Resource Group Template just defined when creating partitions, it will deploy everything in the template automatically.

5.  Access the EJB

Now with the partitions created and started, you can lookup and access the EJB with the following code. We're using the URL for partition1 here, you can also change the URL to access another partition.

  Hashtable<String, String> props = new Hashtable<String, String>();
  props.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
  props.put(Context.PROVIDER_URL, "t3://server1:7001/partition1");
  props.put(Context.SECURITY_PRINCIPAL, user);
  props.put(Context.SECURITY_CREDENTIALS, pass);
  Context ctx = new InitialContext(props);

  BeanIntf bean = (BeanIntf)ctx.lookup("MyEJB"); 
  boolean result = bean.doSomething(); 

6.  Override the data source

If you're feeling something is wrong, you're right. We defined the data source myDS in myRGT, then applied myRGT to both the partitions, now the 2 partitions are sharing the same data source. Normally we don't want this to happen, we need the 2 partitions to work independently without disturbing each other.  How can we do that?

If you want to make partition2 switch to another data source,  you can do that in the Resource Overrides tab of partition2 settings page. You can change the database URL here so another database instance will be used by partition2.  

7.  Change the transaction timeout

As mentioned above, for EJB applications it's supported to dynamically change the transaction timeout value for a particular partition. This can also be accomplished in partition settings page. In the following example, we set the timeout to 15 seconds. This will take affect immediately without asking to reboot.

There're also some other things you can do in the partition settings page, such as defining a work manager or monitoring the resource usage for a particular partition. Spend some time you will find more very useful tools around here.

Concurrency Utilities support in WebLogic Server 12.2.1, Part Five: Multi-tenancy Support

Overview

One of the key features in WLS 12.2.1 is the multi-tenancy support where a single Weblogic Server domain can contain multiple partitions. Please read Part One ~ Part Four prior to this article. Applications deployed to partitions can use the 4 types of concurrent managed objects in the same way as described in Part One ~ Part Four. Applications deployed to partitions can also use global pre-defined concurrent managed object templates, which means when an application is deployed to a partition, WebLogic Server creates concurrent managed objects for this application based on the configuration of global concurrent managed object templates. As you may recall there are server scope Max Concurrent Long Running Requests and Max Concurrent New Threads, please note that they limit long-running request/running threads in the whole server, including partitions.

Configuration

System administrators can define partition scope concurrent managed object templates.

As mentioned in Part One(ManagedExecutorService) and Part Three(ManagedThreadFactory), WebLogic Server provides configurations(Max Concurrent Long Running Requests/Max Concurrent New Threads) to limit the number of concurrent long-running tasks/threads in a ManagedExecutorService/ManagedScheduledExecutorService/ManagedThreadFactory instance, in the global (domain-level) runtime on a server or in the server. Among them, instance scope and server scope limits are applicable to partitions. Besides, system administrators can also define partition scope Max Concurrent Long Running Requests and Max Concurrent New Threads. There are a default Max Concurrent Long Running Requests(50) and a default Max Concurrent New Threads(50) for each partition.

ManagedExecutorService/ManagedScheduledExecutorService/ManagedThreadFactory accepts a long-running task submission/new thread creation only when neither of the 3 limits is exceeded. For instance, there is an application deployed to a partition on a server, when a long-running task is submitted to its default ManagedExecutorServiceRejectedExecutionException will be thrown if there are 10 in progress long-running tasks which are submitted to this ManagedExecutorService, or there are 50 in progress long-running tasks which are submitted to the ManagedExecutorServices/ManagedScheduledExecutorServices in scope of this partition on the server, or there are 100 in progress long-running tasks which are submitted to the ManagedExecutorServices/ManagedScheduledExecutorServices in the server.

Configure Partition Scope Concurrent Managed Object Templates

WebLogic system administrators can configure pre-defined concurrent managed object templates for a partition. When an application is deployed to the partition, WebLogic Server creates concurrent managed object instances based on the configuration of partition scope concurrent managed object templates, and the created concurrent managed object instances are all in scope of this application.

Example-1: Configure a Partition Scope ManagedThreadFactory template using WebLogic Administration Console

Step1: in WebLogic Administration Console, a Partition Scope ManagedThreadFactory template can be created by clicking on the “New” button from the “Summary of Concurrent Managed Object Templates” page. This brings up the "Create a New Managed Thread Factory Template" page where the name and other parameters of the new ManagedThreadFactory template can be specified. Choose the Scope to the partition. In this example, a ManagedThreadFactory template called "testMTFP1" is being created for partition1.

Step2: Once a Partition Scope ManagedThreadFactory template is created, any application in the partition can get its own ManagedThreadFactory instance to use.

@WebServlet("/SomeServlet")

public class SomeServlet extends HttpServlet {

    @Resource(mappedName="testMTFP1")

    ManagedThreadFactory mtf;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        Runnable aTask = new Runnable() {
            ...
        };
        Thread t = mtf.newThread(aTask);

        t.start();
        ...
    }

}

Configure Partition Scope Max Concurrent New Threads & Max Concurrent Long Running Requests

Max Concurrent New Threads of a partition is the limit of running threads created by all ManagedThreadFactories in that partition on a server. Max Concurrent Long Running Requests of a partition is the limit of concurrent long-running tasks submitted to all ManagedExecutorServices and ManagedScheduledExecutorServices in that partition on a server.

In WebLogic Administration Console, Max Concurrent New Threads and Max Concurrent Long Requests of a partition can be edited from the “Settings for <partitionName>” screen. In this example, Max Concurrent New Threads of partition1 is set to 30, Max Concurrent Long Running Requests of partition1 is set to 80

Related Articles:

See for more details Configuring Concurrent Managed Objects in the product documentation.

Concurrency Utilities support in WebLogic Server 12.2.1, Part Four: ContextService

Overview

ContextService is for creating contextual proxy objects. It provides method createContextualProxy to create a proxy object, then proxy object methods will run within the captured context at a later time. 

Weblogic Server provides a preconfigured, default ContextService for each application, and applications can easily use it in web or EJB components without any configuration. Let's begin with a simple example that uses default ContextService.

Example-1: Execute a task with the creator's context using a ExecutorService

Step1: Write the task. In this simple example, the task extends Runnable.

public class SomeTask implements Runnable {

    public void run() {

        // do some work

    }

}

Step2: SomeServlet.java injects the default ContextService, uses the ContextService to create a new contextual object proxy for SomeTask, then submit the contextual object proxy to a Java SE ExecutorService. Each invocation of run() method will have the context of the servlet that created the contextual object proxy.

@WebServlet("/SomeServlet")

public class SomeServlet extends HttpServlet {

    @Resource ContextService cs;

    @Resource ManagedThreadFactory mtf;

    ExecutorService exSvc = Executors.newThreadPool(10, mtf);

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        SomeTask taskInstance = new SomeTask();

        Runnable rProxy = cs.createContextualProxy(taskInstance, Runnable.class);

        Future f =  = exSvc.submit(rProxy);

        // Process the result and reply to the user 

    }

}

Runtime Behavior

Application Scoped Instance

ContextServices are application scoped. Each application has its own default ContextService instance, and the lifecycle of the ContextService instances are bound to the application. Proxy objects created by ContextServices are also application scoped, so that when the application is shut down, invocations to proxied interface methods will fail with an IllegalStateException, and calls to createContextualProxy() will  throw an IllegalArgumentException

WebLogic Server only provides a default ContextService instance for each application, and does not provide any way to configure a ContextService.

Context Propagation

ContextService will capture the application context at contextual proxy object creation, then propagate the captured application context before invocation of contextual proxy object methods, so that proxy object methods can also run with the application context.

Four types of application context are propagated: JNDI, ClassLoader, Security and WorkArea. The propagated context types are the same for four types of the concurrent managed objects.

Related Articles:

See for more details Configuring Concurrent Managed Objects in the product documentation.

Concurrency Utilities support in WebLogic Server 12.2.1, Part Three: ManagedThreadFactory

Overview

ManagedThreadFactory is for creating threads managed by WebLogic Server. It extends from java.util.concurrent.ThreadFactory without new methods, and provides the method newThread from ThreadFactory. It can be used with Java SE concurrency utilities APIs where ThreadFactory is needed. e.g. in java.util.concurrent.Executors.

Weblogic Server provides a preconfigured, default ManagedThreadFactory for each application, and applications can easily use it in web or EJB components without any configuration. Let's begin with a simple example that uses default ManagedThreadFactory in a servlet.

Example-1: Use Default ManagedThreadFactory to Create a Thread in a Servlet

Step1: Write a Runnable, logging data until the thread is interrupted.

public class LoggerTask implements Runnable {

    @Override

    public void run() {

        while (!Thread.interrupted()) {

            // collect data and write them to database or file system

        }

    }

}

Step2: SomeServlet.java injects the default ManagedThreadFactory and use it to create the thread.

@WebServlet("/SomeServlet")

public class SomeServlet extends HttpServlet {

    @Resource ManagedThreadFactory mtf;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        Thread t = mtf.newThread(new LoggerTask());

        t.start();

        // Do something else and reply to the user

    }

}

Runtime Behavior

Application Scoped Instance

ManagedThreadFactories are application scoped. Each application has its own ManagedThreadFactory instances, and the lifecycle of the ManagedThreadFactory instances are bound to the application. Threads created by ManagedThreadFactory are also application scoped, so that when the application is shut down, related threads will be interrupted.

Each application has its own default ManagedThreadFactory instance. Besides, Applications or system administrators can define customized ManagedThreadFactory. Please note that even ManagedThreadFactory templates(see in a later section) defined globally in the console are application scoped during runtime.

Context Propagation

ManagedThreadFactories will capture the application context at ManagedThreadFactory creation(NOT at newThread method invocation), then propagate the captured application context before task execution, so that the task can also run with the application context.

Four types of application context are propagated: JNDI, ClassLoader, Security and WorkArea. The propagated context types are the same for four types of the concurrent managed objects.

Limit of Running Threads

When newThread method is invoked, WebLogic Server creates a new thread. Because an excessive number of running threads can have a negative affect on server performance and stability, WebLogic Server provides configurations(Max Concurrent New Threads) to limit the number of running threads in a ManagedThreadFactory instance, in the global (domain-level) runtime on a server or in the server. By default, the limits are: 10 for a ManagedThreadFactory instance, 50 for the global (domain-level) runtime on a server and 100 for a Server. When either of the limits is exceeded, calls to newThread() method of ManagedThreadFactory return null.

Please note the difference between the global (domain-level) runtime scope Max Concurrent New Threads and the server scope Max Concurrent New Threads. One of the key features in WLS 12.2.1 is the multi-tenancy support where a single Weblogic Server domain can contain multiple partitions. The global (domain-level) runtime Max Concurrent New Threads is the maximum number of threads created by all of the ManagedThreadFactories on the server for global (domain-level) runtime, this excludes threads created within the scope of partitions running on the server, while the server scope Max Concurrent New Threads is the maximum number of threads created by all of the ManagedThreadFactories on the server, including threads created  within the scope of partitions. For partition scope Max Concurrent New Threads, please read Part Five - Multi-tenancy Support.

ManagedThreadFactory returns a new thread only when neither of the 3 limits is exceeded. For instance, there is an application deployed to global (domain-level) runtime on a server, when servlets or EJBs invoke the newThread method of the default ManagedThreadFactory, they will get null if there are 10 in progress threads which are created by this ManagedThreadFactory, or there are 50 in progress threads which are created by the ManagedThreadFactories in scope of global (domain-level) runtime on the server, or there are 100 in progress threads which are created by the ManagedThreadFactories in the server.

There are examples on how to specify the Max Concurrent New Threads in a later section.

Configuration

As mentioned earlier, each application has its own default ManagedThreadFactory. The default ManagedThreadFactory has a default max concurrent new threads(10), and has a default thread priority(Thread.NORM_PRIORITY). There is also a default max concurrent new threads(100) for the whole server. If the default configuration is not good enough you will need to read further for configurations. For instance, when you need to create threads with higher priority, you will need to configure a ManagedThreadFactory; and if there would be more than 100 concurrent running threads in the server, you will need to change the server scope Max Concurrent New Threads.

Configure ManagedThreadFactories

NameMax Concurrent New Threads, and Priority are configured inside a ManagedThreadFactory. Name is a string that identifies the ManagedThreadFactory,Max Concurrent New Threads is the limit of running threads created by this ManagedThreadFactory, and Priority is the priority of threads.

An application can configure a ManagedThreadFactory in DD(weblogic-application.xml/weblogic-ejb-jar.xml/weblogic.xml), and gets the ManagedThreadFactory instance using @Resource(mappedName=<Name of ManagedThreadFactory>), then uses it to create threads. Besides annotation, the application can also bind the ManagedThreadFactory instance to JNDI by specifying <resource-env-description> and <resource-env-ref> in DD, then look it up using JNDI Naming Context, you can read Configuring Concurrent Managed Objects in the product documentation for details.

Also, a WebLogic system administrator can configure pre-defined ManagedThreadFactory templates. When an application is deployed, WebLogic Server creates ManagedThreadFactories based on the configuration of ManagedThreadFactory templates, and the created ManagedThreadFactories are all in scope of this application.

Example-2: Configure a ManagedThreadFactory in weblogic.xml

Step1: defining ManagedThreadFactory:

<!-- weblogic.xml -->

<managed-thread-factory>

    <name>customizedMTF</name>

    <priority>3</priority>

    <max-concurrent-new-threads>20</max-concurrent-new-threads>

</managed-thread-factory>

Step2: obtaining the ManagedThreadFactory instance to use

@WebServlet("/SomeServlet")

public class SomeServlet extends HttpServlet {

    @Resource(mappedName="customizedMTF")

    ManagedThreadFactory mtf;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        Runnable aTask = new Runnable() {
            ...
        };
        Thread t = mtf.newThread(aTask);

        t.start();
        ...
    }

}

Example-3: Configure a ManagedThreadFactory template using WebLogic Administration Console

If there is requirement on multiple applications instead of individual application, you can create ManagedThreadFactory templates globally that are available to all applications. For instance, when you need to create threads from all applications with lower priority, you will need to configure a ManagedThreadFactory template. As mentioned earlier, if there is a ManagedThreadFactory template, WebLogic Server creates a ManagedThreadFactory instance for each application based on the configuration of the template.

Step1: in WebLogic Administration Console, a ManagedThreadFactory template can be created by clicking on the “New” button from the “Summary of Concurrent Managed Object Templates” page. This brings up the "Create a New Managed Thread Factory Template" page where the name and other parameters of the new ManagedThreadFactory template can be specified. In this example, a ManagedThreadFactory template called "testMTF" is being created with priority 3.


Step2: Once a ManagedThreadFactory template is created, any application in the WebLogic Server can get its own ManagedThreadFactory instance to use.

@WebServlet("/SomeServlet")

public class SomeServlet extends HttpServlet {

    @Resource(mappedName="testMTF")

    ManagedThreadFactory mtf;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        Runnable aTask = new Runnable() {
            ...
        };
        Thread t = mtf.newThread(aTask);

        t.start();
        ...
    }

}

Configure Max Concurrent New Threads in global (domain-level) runtime scope or server scope

Example-4: Configure global (domain-level) runtime Scope Max Concurrent New Threads

Max Concurrent New Threads of global (domain-level) runtime is the limit of threads created by ManagedThreadFactories in global (domain-level) runtime on that server, this excludes threads created within the scope of partitions running on that server.

In WebLogic Administration Console, Max Concurrent New Threads of global (domain-level) runtime can be edited from the “Settings for <domainName>” screen. In this example, global (domain-level) runtime Max Concurrent New Threads of mydomain is set to 100.


Example-5: Configure Server Scope Max Concurrent New Threads

Max Concurrent New Threads of a server is the limit of running threads submitted to all ManagedThreadFactories in that server.

In WebLogic Administration Console, Max Concurrent New Threads of a server can be edited from the “Settings for <serverName>” screen. In this example, Max Concurrent New Threads of myserver is set to 200.


Related Articles:

See for more details Configuring Concurrent Managed Objects in the product documentation.

Concurrency Utilities support in WebLogic Server 12.2.1, Part Two: ManagedScheduledExecutorService

Overview

ManagedScheduledExecutorService extends from ManagedExecutorService, all the methods from ManagedExecutorService are supported in ManagedScheduledExecutorService, so prior to this article please read Part One: ManagedExecutorService.

ManagedScheduledExecutorService extends from java.util.concurrent.ScheduledExecutorService, so it also provides methods(schedule, scheduleAtFixedRate, scheduleAtFixedDelay) from ScheduledExecutorService for scheduling tasks to run after a given delay, or periodically. Besides, ManagedScheduledExecutorService provides new methods itself for tasks to run at some custom schedule based on a Trigger. All those tasks are run on threads provided by WebLogic Server.

Weblogic Server provides a preconfigured, default ManagedScheduledExecutorService for each application, and we can easily use it in web or EJB components without any configuration. Let's begin with a simple example that uses default ManagedScheduledExecutorService in a ServletContextListener.

Example-1: Use Default ManagedScheduledExecutorService to Submit a Periodical Task

Step1: Write a task to log data.

public class LoggerTask implements Runnable {

    @Override

    public void run() {

        // collect data and write them to database or file system

    }

}

Step2: SomeListener.java injects the default ManagedScheduledExecutorService, schedules the task periodically in contextInitialized, and cancels the task in contextDestroyed.

@WebListener

public class SomeListener implements ServletContextListener {

    Future loggerHandle = null;

    @Resource ManagedScheduledExecutorService mses;

    public void contextInitialized(ServletContextEvent scEvent) {

        // Creates and executes LoggerTask every 5 seconds, beginning at 1 second later

        loggerHandle = mses.scheduleAtFixedRate(new LoggerTask(), 1, 5, TimeUnit.SECONDS);

    }

    public void contextDestroyed(ServletContextEvent scEvent) {

        // Cancel and interrupt our logger task

        if (loggerHandle != null) {

            loggerHandle.cancel(true);

        }

    }

}

Runtime Behavior

ManagedScheduledExecutorService provides all the features described in Runtime Behavior of Part One: ManagedExecutorService.

As mentioned earlier, ManagedScheduledExecutorService can run task periodically or at some custom schedule, so that a task can run multiple times. Please note that for a long-running task, even if a task can be executed more than once, WebLogic Server creates only one thread for this long-running task at the time of the first run.

Configuration

Configure ManagedScheduledExecutorService

ManagedScheduledExecutorService has the same configurations(Name, Dispatch Policy, Max Concurrent Long Running Requests, and Long Running Priority) as ManagedExecutorService. And the way to get and use the customized ManagedScheduledExecutorService is also similar to ManagedExecutorService.

Example-2: Configure a  ManagedScheduledExecutorService in weblogic.xml

Step1: defining ManagedScheduledExecutorService:

<!-- weblogic.xml -->

<work-manager>

<name>customizedWM</name>

    <max-threads-constraint>

        <name>max</name>

        <count>1</count>

    </max-threads-constraint>

</work-manager>

<managed-scheduled-executor-service>

    <name>customizedMSES</name>

    <dispatch-policy>customizedWM</dispatch-policy>

    <long-running-priority>10</long-running-priority>

    <max-concurrent-long-running-requests>20</max-concurrent-long-running-requests>

</managed-scheduled-executor-service>

Step2: obtaining the ManagedScheduledExecutorService instance to use

@WebServlet("/SomeServlet")

public class SomeServlet extends HttpServlet {

    @Resource(mappedName="customizedMSES")

    ManagedScheduledExecutorService mses;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        Runnable aTask = new Runnable() {
            ...
        };
        mses.schedule(aTask, 5, TimeUnit.SECONDS);
        ...
    }

}


Example-3: Configure a ManagedScheduledExecutorService template using WebLogic Administration Console

Step1: in WebLogic Administration Console, a ManagedScheduledExecutorService template can be created by clicking on the “New” button from the “Summary of Concurrent Managed Object Templates” page. This brings up the "Create a New Managed Scheduled Executor Service Template" page where the name and other parameters of the new ManagedScheduledExecutorService template can be specified. In this example, a ManagedScheduledExecutorService called "testMSES" is being created to map to a pre-defined work manager "testWM".


Step2: Once a ManagedScheduledExecutorService template is created, any application in the WebLogic Server can get its own ManagedScheduledExecutorService instance to use.

@WebServlet("/SomeServlet")

public class SomeServlet extends HttpServlet {

    @Resource(mappedName="testMSES")

    ManagedScheduledExecutorService mses;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        Runnable aTask = new Runnable() {
            ...
        };
        mses.schedule(aTask, 5, TimeUnit.SECONDS);
        ...
    }

}

Related Articles:

See for more details Configuring Concurrent Managed Objects in the product documentation.

Concurrency Utilities support in WebLogic Server 12.2.1, Part One: ManagedExecutorService

Overview

ManagedExecutorService is for running tasks asynchronously on threads provided by WebLogic Server. It extends from java.util.concurrent.ExecutorService without new methods, it provides methods(execute, submit, invokeAll, invokeAny) from ExecutorService, and its lifecycle methods(awaitTermination, isTerminated, isShutdown, shutdown, shutdownNow) are disabled with IllegalStateException.

Weblogic Server provides a preconfigured, default ManagedExecutorService for each application, and applications can easily use it in web or EJB components without any configuration. Let's begin with a simple example that uses default ManagedExecutorService in a servlet.

Example-1: Use Default ManagedExecutorService to Submit an Asynchronous Task in a Servlet

Step1: Write an asynchronous task. Asynchronous tasks must implement either java.util.concurrent.Callable or java.lang.Runnable. A task can optionally implement javax.enterprise.concurrent.ManagedTask(see JSR236 specification) to provide identifying information, a ManagedTaskListener or additional execution properties of the task.

public class SomeTask implements Callable<Integer> {

    public Integer call() {

        // Interact with a database, then return answer.

    }

}

Step2: SomeServlet.java injects the default ManagedExecutorService and submit the task to it.

@WebServlet("/SomeServlet")

public class SomeServlet extends HttpServlet {

    @Resource ManagedExecutorService mes;

     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // Create and submit the task instances

        Future<Integer> result = mes.submit(new SomeTask());

        // do something else

        try {

            // Wait for the result

            Integer value = result.get();

            // Process the result and reply to the user

        } catch (InterruptedException | ExecutionException e) {

            throw new ServletException("failed to get result for SomeTask", e);

        }

    }

}

Runtime Behavior


Application Scoped Instance

There are two applications(A in red and B in green) in the above figure. You can see that the two applications are submitting tasks to different ManagedExecutorService instances, this is true because ManagedExecutorServices are application scoped. Each application has its own ManagedExecutorService instances, and the lifecycle of the ManagedExecutorService instances are bound to the application. Asynchronous tasks submitted to ManagedExecutorServices are also application scoped, so that when the application is shut down, related asynchronous tasks/threads will be cancelled/interrupted.

Each application has its own default ManagedExecutorService instance. Besides, Applications or system administrators can define customized ManagedExecutorService. Please note that even ManagedExecutorService templates(see in a later section) defined globally in the console are application scoped during runtime.

Context Propagation

In the above figure you can see that when application A is submitting a task, the task is wrapped with the context of application A, whereas when application B is submitting a task, the task is wrapped with the context of application B. This is true because ManagedExecutorServices will capture the application context at task submission, then propagate the captured application context before task execution, so that the task can also run with the application context.

Four types of application context are propagated: JNDI, ClassLoader, Security and WorkArea. The propagated context types are the same for four types of the concurrent managed objects.

Self Tuning(for short-running tasks)

In the above figure you can see that ManagedExecutorServices submit short-running tasks to WorkManagers(see Workload Management in WebLogic Server 9.0 for overview of WebLogic work managers), and create a new thread for each long-running task. As you may know, WebLogic Server diagnoses a thread as stuck if it is continually working (not idle) for a set period of time(default is 10 minutes), so normally if a task would last longer than that period of time, it can be a long-running task. You can set ManagedTask.LONGRUNNING_HINT property(see JSR236 specification) to "true" to make it run as a long-running task.

Each ManagedExecutorService is associated with an application-scoped WorkManager. By default, ManagedExecutorServices are associated with the application default WorkManager. Applications or system administrators can specify Dispatch Policy to associate a ManagedExecutorService with a specific application-scoped WorkManager. There are examples on how to use the dispatch policy in a later section.

By associating a ManagedExecutorService with a WorkManager, WebLogic Server utilize the threads in the single thread pool to run asynchronous tasks from applications, so that asynchronous tasks can also be dynamically prioritized together with servlet or RMI requests.

Limit of Concurrent Long-running Requests

As mentioned earlier long-running tasks do not utilize the threads in the single thread pool, WebLogic Server creates a new thread for each task. Because an excessive number of running threads can have a negative affect on server performance and stability, WebLogic Server provides configurations(Max Concurrent Long Running Requests) to limit the number of concurrent long-running tasks in a ManagedExecutorService/ManagedScheduledExecutorService instance, in the global (domain-level) runtime on a server or in the server. By default, the limits are: 10 for a ManagedExecutorService/ManagedScheduledExecutorService instance, 50 for the global (domain-level) runtime on a server and 100 for a Server. When either of the limits is exceeded, ManagedExecutorService/ManagedScheduledExecutorService rejects long-running tasks submissions by throwing a RejectedExecutionException.

Please note the difference between the global (domain-level) runtime scope Max Concurrent Long Running Requests and the server scope Max Concurrent Long Running Requests. One of the key features in WLS 12.2.1 is the multi-tenancy support where a single Weblogic Server domain can contain multiple partitions. The global (domain-level) runtime scope Max Concurrent Long Running Requests is the maximum number of concurrent long-running tasks submitted by all of the ManagedExecutorServices/ManagedScheduledExecutorServices on the server for global (domain-level) runtime, this excludes concurrent long-running tasks submitted within the scope of partitions running on the server, while the server scope Max Concurrent Long Running Requests is the maximum number of concurrent long-running tasks submitted by all of the ManagedExecutorServices/ManagedScheduledExecutorServices on the server, including concurrent long-running tasks submitted within global (domain-level) runtime and partitions. For partition scope Max Concurrent Long Running Requests, please read Part Five - Multi-tenancy Support.

ManagedExecutorService/ManagedScheduledExecutorService accepts a concurrent long-running task submission only when neither of the 3 limits is exceeded. For instance, there is an application deployed to global (domain-level) runtime on a server, when a long-running task is submitted to its default ManagedExecutorServiceRejectedExecutionException will be thrown if there are 10 in progress long-running tasks which are submitted to this ManagedExecutorService, or there are 50 in progress long-running tasks which are submitted to the ManagedExecutorServices/ManagedScheduledExecutorServices in scope of global (domain-level) runtime on the server, or there are 100 in progress long-running tasks which are submitted to the ManagedExecutorServices/ManagedScheduledExecutorServices in the server.

There are examples on how to specify the Max Concurrent Long Running Requests in a later section.

Configuration

As mentioned earlier, each application has its own default ManagedExecutorService. The default ManagedExecutorService is associated with the default WorkManager, has a default max concurrent long running requests(10), and has a default thread priority(Thread.NORM_PRIORITY). There is also a default max concurrent long running requests(100) for the whole server. If the default configuration is not good enough you will need to read further for configurations. For instance, when you need to associate short-running tasks to a pre-defined WorkManager with higher priority, you will need to configure a ManagedExecutorService; and if there would be more than 100 concurrent long-running tasks in the server, you will need to change the server scope Max Concurrent Long Running Requests.

Configure ManagedExecutorServices

Name, Dispatch Policy, Max Concurrent Long Running Requests, and Long Running Priority are configured inside a ManagedExecutorService. Name is a string that identifies the ManagedExecutorServiceDispatch Policy is the name of the WorkManager to which the short-running tasks are submitted, Max Concurrent Long Running Requests is the limit of concurrent long-running tasks submitted to this ManagedExecutorService, and Long Running Priority is the priority of the threads created for long-running tasks.

An application can configure a ManagedExecutorService in DD(weblogic-application.xml/weblogic-ejb-jar.xml/weblogic.xml), and gets the ManagedExecutorService instance using @Resource(mappedName=<Name of ManagedExecutorService>), then submits a task to it. Besides annotation, the application can also bind the ManagedExecutorService instance to JNDI by specifying <resource-env-description> and <resource-env-ref> in DD, then look it up using JNDI Naming Context, you can read Configuring Concurrent Managed Objects in the product documentation for details.

Also, a WebLogic system administrator can configure pre-defined ManagedExecutorService templates. When an application is deployed, WebLogic Server creates ManagedExecutorServices based on the configuration of ManagedExecutorService templates, and the created ManagedExecutorServices are all in scope of this application.

Example-2: Configure a ManagedExecutorService in weblogic.xml

Step1: defining ManagedExecutorService:

<!-- weblogic.xml -->

<work-manager>

<name>customizedWM</name>

    <max-threads-constraint>

        <name>max</name>

        <count>1</count>

    </max-threads-constraint>

</work-manager>

<managed-executor-service>

    <name>customizedMES</name>

    <dispatch-policy>customizedWM</dispatch-policy>

    <long-running-priority>10</long-running-priority>

    <max-concurrent-long-running-requests>20</max-concurrent-long-running-requests>

</managed-executor-service>

Step2: obtaining the ManagedExecutorService instance to use

@WebServlet("/SomeServlet")

public class SomeServlet extends HttpServlet {

    @Resource(mappedName="customizedMES")

     ManagedExecutorService mes;

     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

         Runnable aTask = new Runnable() {
             ...
         };
         mes.submit(aTask);
         ...
    }

}

Example-3: Configure a ManagedExecutorService template using WebLogic Administration Console

If there is requirement on multiple applications instead of individual application, you can create ManagedExecutorService templates globally that are available to all applications. For instance, when you need to run short-running tasks from all applications with lower priority, you will need to configure a ManagedExecutorService template . ManagedExecutorService templates are also useful in Batch jobs. As mentioned earlier, if there is a ManagedExecutorService template, WebLogic Server creates a ManagedExecutorService instance for each application based on the configuration of the template.

Step1: in WebLogic Administration Console, a ManagedExecutorService template can be created by clicking on the “New” button from the “Summary of Concurrent Managed Object Templates” page. This brings up the "Create a New Managed Executor Service Template" page where the name and other parameters of the new ManagedExecutorService template can be specified. In this example, a ManagedExecutorService called "testMES" is being created to map to a pre-defined work manager "testWM".


Step2: Once a ManagedExecutorService template is created, any application in the WebLogic Server can get its own ManagedExecutorService instance to use.

@WebServlet("/SomeServlet")

public class SomeServlet extends HttpServlet {

    @Resource(mappedName="testMES")

    ManagedExecutorService mes;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        Runnable aTask = new Runnable() {
            ...
        };
        mes.submit(aTask);
        ...
    }

}

Configure Max Concurrent Long Running Requests Running in global (domain-level) runtime scope or server scope

Example-4: Configure global (domain-level) runtime Scope Max Concurrent Long Running Requests

Max Concurrent Long Running Requests of global (domain-level) runtime is the limit of concurrent long-running tasks submitted to all ManagedExecutorServices and ManagedScheduledExecutorServices in global (domain-level) runtime on that server, this excludes long-running tasks submitted within the scope of partitions running on that server.

In WebLogic Administration Console, Max Concurrent Long Requests of global (domain-level) runtime can be edited from the “Settings for <domainName>” screen. In this example, global (domain-level) runtime Max Concurrent Long Running Requests for mydomain is set to 80.

Example-5: Configure Server Scope Max Concurrent Long Running Requests

Max Concurrent Long Running Requests of a server is the limit of concurrent long-running tasks submitted to all ManagedExecutorServices and ManagedScheduledExecutorServices in that server.

In WebLogic Administration Console, Max Concurrent Long Requests of a server can be edited from the “Settings for <serverName>” screen. In this example, Max Concurrent Long Running Requests of myserver is set to 200.


Related Articles:

See for more details Configuring Concurrent Managed Objects in the product documentation.

Concurrency Utilities support in WebLogic Server 12.2.1

As part of its support for Java EE 7, WebLogic Server 12.2.1 supports the Java EE Concurrency Utilities(JSR236) specification.

This specification provides a simple, standardized API(4 types of managed objects) for using concurrency from Java EE application components(such as servlets and EJBs). The 4 types of concurrent managed objects implement these interfaces in javax.enterprise.concurrent package: ManagedExecutorService, ManagedScheduledExecutorService, ManagedThreadFactory, ContextService.

If you are still using common Java SE concurrency APIs such as java.lang.Thread or java.util.Timer directly in your servlets or EJBs, you are strongly recommended to use java EE Concurrency Utilities instead. Threads created by using Java SE concurrency APIs are not managed by WebLogic Server, so that services and resources provided by WebLogic Server are typically unable to be reliably used from these un-managed threads.  By using java EE Concurrency Utilities, asynchronous tasks run on WebLogic Server-managed threads. Since WebLogic Server has knowledge of these threads/asynchronous tasks, it can manage them by:

  • Providing the proper execution context, including JNDI, ClassLoader, Security, WorkArea
  • Submitting short-running tasks to the single server-wide self-tuning thread pool to make them prioritized based on defined rules and run-time metrics
  • Limiting the number of threads for long-running tasks to prevent negative affect on server performance and stability
  • Managing the lifecycle of asynchronous tasks by interrupting threads/cancelling tasks when the application shuts down

CommonJ API(providing context aware Work Managers and Timers) is WebLogic Server specific, and is the predecessor of Java EE Concurrency Utilities. Comparing to CommonJ API, Java EE Concurrency Utilities is more standardized and easier to use, and provides more functions like custom scheduling, ContextService, ManagedThreadFactory.

Read these articles for details:

See for more details Configuring Concurrent Managed Objects in the product documentation.

Wednesday Nov 18, 2015

Patching Oracle Home Across your Domain with ZDT Patching

Now it’s time for the really good stuff!  In this post, you will see how Zero Downtime (ZDT) Patching can be used to rollout a patched WebLogic OracleHome directory to all your managed servers (and optionally to your AdminServer) without incurring any downtime or loss of session data for your end-users.

This rollout, like the others, is based on the controlled rolling shutdown of nodes, and using Oracle Traffic Director (OTD) load balancer to route user requests around the offline node. The difference with this rollout is what happens when the managed servers are shut down. In this case, when the managed servers are shutdown, the rollout will actually move the current OracleHome directory to a backup location, and replace it with a patched OracleHome directory that the administrator has prepared, verified, and distributed in advance. (More on the preparation in a moment)

When everything has been prepared, starting the rollout is simply a matter of issuing a WLST command like this one:

rolloutOracleHome(“Cluster1”, “/pathTo/PatchedOracleHome.jar”, “/pathTo/BackupCurrentOracleHome”, “FALSE”)

The AdminServer will then check that the PatchedOracleHome.jar file exists everywhere that it should, and it will begin the rollout. Note that the “FALSE” flag simply indicates that this is not a domain level rollback operation where we would be required to update the AdminServer last instead of first.

In order to prepare the patched OracleHome directory, as mentioned above, the user can start with a copy of a production OracleHome, usually in a test (non-production) environment, and apply the desired patches in whatever way is already familiar to them. Once this is done, the administrator uses the included CIE tool copyBinary to create a distributable jar archive of the OracleHome. Once the jar archive of the patched OracleHome directory has been created, it can be distributed to all of the nodes that will be updated. Note that it needs to reside on the same path for all nodes. With that, the preparation is complete and the rollout can begin!

Be sure to check back soon to read about how the preparation phase has been automated as well by integrating ZDT Patching with another new tool called OPatchAuto.


For more information about updating OracleHome with Zero Downtime Patching, view the documentation.

Monday Nov 16, 2015

Weblogic 12.2.1 Multitenancy Support for Resource Adapter

One of the key features in WLS 12.2.1 is the multi-tenancy support, you can learn more about its concept in Tim Quinn's blog:Domain Partitions for Multi-tenancy in WebLogic Server. For resource adapter, besides deploying it to domain partition, you can also deploy a resource adapter to partition's resource group or resource group template. This can be done by selecting resource group scope or resource group template scope while deploying resource adapter in console. Following graph shows the deployment page in console. In the example graph, we have a resource group Partition1-rg in Partition1 and a resource group template TestRGT:

Deploy RA to MT in Console

When you select 'Global' scope, the resource adapter will be deployed to domain partition. If selecting 'TestRGT template', the resource adapter will be deployed to resource group template TestRGT, and if Partition1's resource group references TestRGT, the resource adapter will be deployed to Partition1. If selecting 'Partition1-rg in Partition1', the resource adapter will be deployed to Partition1. 

You can learn more about multi-tendency deployment in Hong Zhang's blog: Multi Tenancy Deployment.

If you deploy resource adapters to different partitions, these resources in different partitions will not interfere each other, because:

  1. Resource adapter's JNDI resources in one partition can not be looked up by another partition, you can only lookup resource adapter resources being bound in same partition.
  2. Resource adapter classes packaged in resource adapter archive are loaded by different classloaders when they are deployed to different partitions. You do not need to worry about mistakenly using some resource adapter classes loaded by another partition.
  3. If you somehow get a reference to one of the following resource adapter's resource objects which belongs to another partition, you still can not use it. You will get a exception if you calling some of the methods of that object.
    • javax.resource.spi.work.WorkManager
    • javax.resource.spi.BootstrapContext
    • javax.resource.spi.ConnectionManager
    • javax.validation.Validator
    • javax.validation.ValidatorFactory
    • javax.enterprise.inject.spi.BeanManager
    • javax.resource.spi.ConnectionEventListener

After having resource adapter deployed,  you can access domain resource adapter's runtime mbean through 'ConnectorServiceRuntime' directory under ServerRuntime, using WebLogic Scripting Tool (WLST):

View Connector RuntimeMBean in WLST

In above example, we have a resource adapter named 'jca_ra' deployed in domain partition, so we can see it's runtime mbean under ConnectorServiceRuntime/ConnectorService. jms-internal-notran-adp and jms-internal-xa-adp are also listed here, they are weblogic internal resource adapters.

But how can we monitor resource adapters deployed in partition? they are under PartitionRuntimes:

View MT Connector RuntimeMBean in WLST

In above example, we have a resource adapter named 'jca_ra' deployed in Partition1.


You can also get resource adapter's runtimembean through JMX(see how to access runtimembean using JMX):

      JMXServiceURL serviceURL = new JMXServiceURL("t3", hostname, port,          
                             "/jndi/weblogic.management.mbeanservers.domainruntime");
      Hashtable h = new Hashtable();
      h.put(Context.SECURITY_PRINCIPAL, user);
      h.put(Context.SECURITY_CREDENTIALS, passwd);
      h.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES,
                            "weblogic.management.remote");
      h.put("jmx.remote.x.request.waiting.timeout", new Long(10000));
      JMXConnector connector = JMXConnectorFactory.connect(serviceURL, h);
      MBeanServerConnection connection = connector.getMBeanServerConnection();
      Set<ObjectName> names = connection.queryNames(new ObjectName(
                            "*:Type=ConnectorComponentRuntime,Name=jca_ra,*"), null);
      for (ObjectName oname : names) {
          Object o = MBeanServerInvocationHandler.newProxyInstance(connection, oname, 
                               ConnectorComponentRuntimeMBean.class, false);
          System.out.println(o);
      }

Running above example code in a domain which has a resource adapter named 'jca_ra' deployed to both domain and Partition1, you will get following result:

[MBeanServerInvocationHandler]com.bea:Name=jca_ra,ServerRuntime=admin,Location=admin,

                                Type=ConnectorComponentRuntime,ApplicationRuntime=jca_ra

[MBeanServerInvocationHandler]com.bea:Name=jca_ra,ServerRuntime=admin,Location=admin,

                              Type=ConnectorComponentRuntime,ApplicationRuntime=jca_ra,PartitionRuntime=Partition1

You can see the connection pool runtime mbean(ConnectorComponentRuntime) of the resource adapter which is deployed to Partition1 has a valid PartitionRuntime attribute. So you can query Partition1's resource adapter's runtime mbean by following code:

connection.queryNames(new ObjectName(

                   "*:Type=ConnectorComponentRuntime,Name=jca_ra,PartitionRuntime=Partition1,*"), null);

About

The official blog for Oracle WebLogic Server fans and followers!

Stay Connected

Search

Archives
« February 2016
SunMonTueWedThuFriSat
 
1
2
3
4
5
6
7
8
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
     
       
Today