Managed Objects

This chapter describes the managed objects provided by Jakarta Concurrency by using examples.

1. ManagedExecutorService

The jakarta.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 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>
                <stuck-thread-handling>
                    <max-stuck-thread-time>3600000</max-stuck-thread-time>
                    <action-on-stuck-thread>None</action-on-stuck-thread>
                    <stuck-thread-check-period>300000</stuck-thread-check-period>
                </stuck-thread-handling>
            </thread-pool>
        </managed-executor-service>
    </resources>
    ...
</domain>

The configuration items are as follows.

  • Basic Items

    Item Description

    Export Name

    Sets the name that will be used to register a managed executor service with the naming server.

    Long Running Task

    Indicates whether a task run by a managed executor service is long-running. Boolean type.

  • Thread Pool

    Configures the thread pool used in a managed executor service.

    Item Description

    Min

    Minimum number of threads managed by a thread pool.

    Max

    Maximum number of threads managed by a thread pool.

    Keep Alive Time

    Keep-alive time for inactive threads. If a thread pool contains more than the minimum number of threads, inactive threads for the spcified time will be automatically removed. If this option is set to 0, threads will not be removed.

    Queue Size

    Size of the queue which stores the application objects processed by a thread pool.

  • Stuck Thread Handling

    Configures how to handle a thread when it is occupied by a specific task for longer than specified.

    Item Description

    Max Stuck Thread Time

    Length of time before a thread is identified as stuck.

    Action On Stuck Thread

    Action to take when stuck threads are detected. Choose one of the following:

    • None: Takes no action.

    • Interrupt: Sends an interrupt signal by calling java.lang.Thread#interrupt().

    • IgnoreAndReplace: Ignores the Stuck Thread and replace it with a new thread. When the Stuck state is released, the ignored thread is discarded.

    • Warning: Leaves a thread dump with a warning in the log.

    Stuck Thread Check Period

    Interval in milliseconds between each consecutive check for the stuck thread status.

    User Warning Class

    If action-on-stuck-thread is set to Warning, the default value for this option is thread dump. However, you can write a class to execute the action you want by configuring this option. The class must implement the jeus.util.pool.Warning in jclient.jar. After writing the class, locate in SERVER_HOME/lib/application.

Application Example

The following is an example of an application using ManagedExecutorService.

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
    }
}

2. ManagedScheduledExecutorService

The jakarta.enterprise.concurrent.ManagedScheduledExecutorService 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 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>
             <stuck-thread-handling>
                 <max-stuck-thread-time>3600000</max-stuck-thread-time>
                 <action-on-stuck-thread>None</action-on-stuck-thread>
                 <stuck-thread-check-period>300000</stuck-thread-check-period>
             </stuck-thread-handling>
         </thread-pool>
     </managed-scheduled-executor-service>
 </resources>
 ...
</domain>

The configuration items are as follows.

  • Basic Items

    Item Description

    Export Name

    Sets the name that will be used to register a managed scheduler executor service with the JNDI naming server.

    Long Running Task

    Indicates whether a task run by a managed scheduled executor service is long-running. Boolean type.

  • Thread Pool

    Configures the thread pool used in a managed executor service.

    Item Description

    Min

    Minimum number of threads managed by a thread pool.

    Max

    Maximum number of threads managed by a thread pool.

    Keep Alive Time

    Keep-alive time for inactive threads. If a thread pool contains more than the minimum number of threads, inactive threads for the specified time will be automatically removed. If this option is set to 0, threads will not be removed.

    Queue Size

    Size of the queue which stores the application objects processed by a thread pool.

  • Stuck Thread Handling

    Configures how to handle a thread when it is occupied by a specific task for longer than specified.

    Item Description

    Max Stuck Thread Time

    Length of time before a thread is identified as stuck.

    Action On Stuck Thread

    Action to take when stuck threads are detected. Choose one of the following:

    • None: Takes no action.

    • Interrupt: Sends an interrupt signal by calling java.lang.Thread#interrupt().

    • IgnoreAndReplace: Ignores the Stuck Thread and replace it with a new thread. When the Stuck state is released, the ignored thread is discarded.

    • Warning: Leaves a thread dump with a warning in the log.

    Stuck Thread Check Period

    Interval in milliseconds between each consecutive check for the stuck thread status.

    User Warning Class

    If action-on-stuck-thread is set to Warning, the default value for this option is thread dump. However, you can write a class to execute the action you want by configuring this option. The class must implement the jeus.util.pool.Warning in jclient.jar. After writing the class, locate in SERVER_HOME/lib/application.

Application Example

The following is an example of an application using ManagedScheduledExecutorService.

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);
    }
}

3. ContextService

The ContextService function provides a method for creating managed tasks instead of ExecutorService. By using the ContextService function, you 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. Before executing a task by using a dynamic proxy, you 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 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>

The configuration items are as follows.

  • Basic Items

    Item Description

    Export Name

    Sets the name that will be used to register a context service with the JNDI naming server.

Application Example

The following is an example of an application using ContextService.

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 {
        // Regular 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);
            }
        };

        // Convert a regular task to a contextual task through ContextService
        cs.createContextualProxy(simpleTask, Runnable.class);

        // Pass a contextual task to the Java SE executor
        ExecutorService es = Executors.newFixedThreadPool(1);
        es.submit(simpleTask);
    }
}

4. ManagedThreadFactory

The jakarta.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 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>

The configuration items are as follows.

  • Basic Items

    Item Description

    Export Name

    Sets the name that will be used to register a managed thread factory with the JNDI naming server.

    Thread Priority

    Sets thread priority. (Default value: 5)

Application Example

The following is an example of an application using ManagedThreadFactory.

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 {
        // Regular 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);
            }
        };

        // Execute simpleTask in a thread provided by ManagedThreadFactory
        mtf.newThread(simpleTask).start();

        // Or pass ThreadFactory as a parameter of ThreadPoolExecutor
        Executor e = new ThreadPoolExecutor(5, 10, 6L, TimeUnit.MINUTES,
                        new ArrayBlockingQueue<Runnable>(4096), mtf);
        e.execute(new SimpleTask());
    }
}