Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The recommended way to create threads in a Java EE environment, is with the Concurrency Utils API, which is part of the EE7 specification.</p> <p>By using this API your new thread will be created, and managed by the container, guaranteeing that all EE services are available to your thread (eg security, transactions).</p> <p>The examples below are taken from my own site <a href="http://blog.chris-ritchie.com/2013/09/simple-concurrency-example-with-wildfly.html">here</a> and <a href="http://blog.chris-ritchie.com/2013/10/managed-thread-factory-example-in-wildfly.html">here</a></p> <p><strong>Using a ManagedExecutorService</strong></p> <p>To create a new thread using a ManagedExecutorService, first create a task object that implements Callable. Within the call() method we will define the work that we want carried out in a separate thread.</p> <pre><code>public class ReportTask implements Callable&lt;Report&gt; { Logger logger = Logger.getLogger(getClass().getSimpleName()); public Report call() { try { Thread.sleep(3000); catch (InterruptedException e) { logger.log(Level.SEVERE, "Thread interrupted", e); } return new Report(); } } </code></pre> <p>Then we need to invoke the task by passing it though to the submit() method of the ManagedExecutorService.</p> <pre><code>@Stateless public class ReportBean { @Resource private ManagedExecutorService executorService; public void runReports() { ReportTask reportTask = new ReportTask(); Future&lt;Report&gt; future = executorService.submit(reportTask); } } </code></pre> <p><strong>Using a ManagedThreadFactory</strong></p> <p>First create a Runnable task which will define what work is to be done in the background.</p> <pre><code>public class ReportTask implements Runnable { Logger logger = Logger.getLogger(getClass().getSimpleName()); public void run() { try { //do your background task Thread.sleep(10000); } catch (InterruptedException e) { logger.log(Level.SEVERE, "Thread interrupted", e); } } } </code></pre> <p>To get a container managed thread, we simply ask the ManagedThreadFactory for a new thread, and pass it our Runnable instance. To start the thread we call start().</p> <pre><code>@Stateless public class ReportBean { @Resource private ManagedThreadFactory threadFactory; public void runReports() { ReportTask reportTask = new ReportTask(); Thread thread = threadFactory.newThread(reportTask); thread.start(); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload