Chapter 2. Managed Objects

Table of Contents

2.1. ManagedExecutorService
2.2. ManagedScheduledExecutorService
2.3. ContextService
2.4. ManagedThreadFactory

This chapter describes the managed objects provided in Concurrency Utilities for Java EE by using examples.

2.1. ManagedExecutorService

The javax.enterprise.concurrent.ManagedExecutorService interface inherits Java SE's java.util.concurrent.ExecutorService. Just like ExecutorService, it is used for executing asynchronous tasks, and the application server maintains the context of the tasks that have been executed asynchronously.

Resource Definition Example

The following is an example of defining ManagedExecutorService as a resource.

[Example 2.1] Example of Defining ManagedExecutorService as a Resource: <<domain.xml>>

<domain>
    ...
    <server>
       <data-sources>
           <data-source>testdb</data-source>
       </data-sources>
       <managed-executor-service>mes1</managed-executor-service>
    </server>

    <resources>
        <managed-executor-service>
            <export-name>mes1</export-name>
            <long-running-task>true</long-running-task>
            <thread-pool>
                <min>10</min>
                <max>20</max>
                <keep-alive-time>60000</keep-alive-time>
                <queue-size>4096</queue-size>
            </thread-pool>
        </managed-executor-service>
    </resources>
    ...
</domain>


Application Example

The following is an example of using ManagedExecutorService.

[Example 2.2] Example of an Application using ManagedExecutorService

public class AppServlet extends HTTPServlet implements Servlet {
    // Retrieve our executor instance.
    @Resource(name=mes1”)
    ManagedExecutorService mes;

    protected void doPost(HttpServletRequest req, HttpServletResponse
            resp) throws ServletException, IOException {
        ArrayList<Callable> builderTasks = new ArrayList<Callable>();
        builderTasks.add(new AccountTask(reqID, accountID));
        builderTasks.add(new InsuranceTask(reqID, accountID));

        // Submit the tasks and wait.
        List<Future<Object>> results = mes.invokeAll(builderTasks);

        AccountInfo accountInfo = (AccountInfo) results.get(0).get();
        InsuranceInfo insInfo = (InsuranceInfo) results.get(1).get();
        // Process the results
    }
}

WebAdmin Example

ManagedExecutorService can be configured by selecting [Resources] > [Concurrency Utilities Resource] on the left menu of WebAdmin.

[Figure 2.1] Configuring ManagedExecutorService in WebAdmin

Configuring ManagedExecutorService in WebAdmin


2.2. ManagedScheduledExecutorService

The javax.enterprise.concurrent.ManagedExecutorService interface inherits all the functions of ManagedExecutorService, as well as the functions of Java SE's java.util.concurrent.ScheduledExecutorService. This enables the interface to be able to execute tasks periodically/delays. In addition, tasks can be controlled by using the trigger and ManagedTaskListener interfaces.

Resource Definition Example

The following is an example of defining ManagedScheduledExecutorService as a resource.

[Example 2.3] Example of Defining ManagedScheduledExecutorService as a Resource: <<domain.xml>>

<domain>
    ...
    <server>
       <data-sources>
          <data-source>testdb</data-source>
       </data-sources>
       <managed-scheduled-executor-service>mses1</managed-scheduled-executor-service>
    </server>
    <resources>
        <managed-scheduled-executor-service>
            <export-name>mses1</export-name>
            <long-running-task>true</long-running-task>
            <thread-pool>
                <min>10</min>
                <max>20</max>
                <keep-alive-time>60000</keep-alive-time>
                <queue-size>4096</queue-size>
            </thread-pool>
        </managed-scheduled-executor-service>
    </resources>
    ...
</domain>

Application Example

The following is an example of an application using ManagedScheduledExecutorService.

[Example 2.4] Example of an Application using ManagedScheduledExecutorService

public class AppServlet extends HTTPServlet implements Servlet {
    @Resource(name=mses1”)
    ManagedScheduledExecutorService mses;

    protected void doPost(HttpServletRequest req, HttpServletResponse
            resp) throws ServletException, IOException {
        Runnable printTask = new Runnable() {
            @Override
            public void run() {
                System.out.println(System.currentTimeMillis());
            }
        };
        // printTask is executed every 5 seconds
        mses.schedule(printTask, 5, TimeUnit.SECONDS);
    }
}

WebAdmin Example

The following is an example of configuring ManagedScheduledExecutorService in WebAdmin.

[Figure 2.2] Configuring ManagedScheduledExecutorService in WebAdmin

Configuring ManagedScheduledExecutorService in WebAdmin


2.3. ContextService

Provides a method for creating managed tasks using ContextService, instead of using ExecutorService. By using this function, users do not have to worry about the context when creating a task, as the context is maintained when a task is executed in the application server. To explain more in detail, before executing a task by using a dynamic proxy, configure the context in the thread, and then execute the task. Then, after all tasks have been performed, restore the context.

Resource Definition Example

The following is an example of defining ContextService as a resource.

[Example 2.5] Example of Defining ContextService as a Resource: <<domain.xml>>

<domain>
    ...
    <server>
        <data-sources>
            <data-source>testdb</data-source>
        </data-sources>
        <context-service>cs1</context-service>
    </server>

    <resources>
        <context-service>
            <export-name>cs1</export-name>
        </context-service>
    </resources>
    ...
</domain>

Application Example

The following is an example of an application using ContextService.

[Example 2.6] Example of an Application using ContextService

public class AppServlet extends HTTPServlet implements Servlet {
    @Resource(name=cs1”)
    ContextService cs;

    protected void doPost(HttpServletRequest req, HttpServletResponse
            resp) throws ServletException, IOException {
        // General Runnable task
        Runnable simpleTask = new Runnable() {
            @Override
            public void run() {
                int sum = 0;
                for (int i = 0; i < 10; i++) { sum += i; }
                System.out.println(sum);
            }
        };

        // Transformed a general task into a contextual task by using ContextService.
        cs.createContextualProxy(simpleTask, Runnable.class);

        // Submitted the contextual task to the executor provided in SE.
        ExecutorService es = Executors.newFixedThreadPool(1);
        es.submit(simpleTask);
    }
}

WebAdmin Example

The following is an example of configuring ContextService in WebAdmin.

[Figure 2.3] Configuring ContextService in WebAdmin

Configuring ContextService in WebAdmin


2.4. ManagedThreadFactory

The javax.enterprise.concurrent.ManagedThreadFactory interface inherits Java SE's java.util.concurrent.ThreadFactory function, which enables it to create threads. Typically, it is used to submit ThreadFactory as the constructor’s parameter when creating ThreadPoolExecutor. Therefore, even in Java SE's concurrency API, the context for a task can be maintained when a worker thread executes a task.

Resource Definition Example

The following is an example of defining ManagedThreadFactory as a resource.

[Example 2.7] Example of Defining ManagedThreadFactory as a Resource: <<domain.xml>>

<domain>
    ...
    <server>
        <data-sources>
            <data-source>testdb</data-source>
        </data-sources>
        <managed-thread-factory>mtf1</managed-thread-factory>
    </server>

    <resources>
        <managed-thread-factory>
            <export-name>mtf1</export-name>
            <thread-priority>5</thread-priority>
        </managed-thread-factory>
    </resources>
    ...
</domain>

Application Example

The following is an example of an application using ManagedThreadFactory.

[Example 2.8] Example of an Application using ManagedThreadFactory

public class AppServlet extends HTTPServlet implements Servlet {
    // Retrieve our executor instance.
    @Resource(name=mtf1”)
    ManagedThreadFactory mtf;

    protected void doPost(HttpServletRequest req, HttpServletResponse
            resp) throws ServletException, IOException {
        // General runnable task
        Runnable simpleTask = new Runnable() {
            @Override
            public void run() {
                int sum = 0;
                for (int i = 0; i < 10; i++) { sum += i; }
                System.out.println(sum);
            }
        };

        // simpleTask is executed in a thread provided in ManagedThreadFactory.
        mtf.newThread(simpleTask).start();

        // Or send it to ThreadFactory by using ThreadPoolExecutor's parameters.
        Executor e = new ThreadPoolExecutor(5, 10, 6L, TimeUnit.MINUTES, new ArrayBlockingQueue<Runnable>(4096), mtf);
        e.execute(new SimpleTask());
    }
}

WebAdmin Example

The following is an example of configuring ManagedThreadFactory in WebAdmin.

[Figure 2.4] Configuring ManagedThreadFactory in WebAdmin

Configuring ManagedThreadFactory in WebAdmin