Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create threads in Java EE environment?

I have a requirement where I have to persist some data in a table and the persisting may take sometime. Basically I want to persist a log. I don't want the execution to wait till the persisting finishes.

I know I have to use threads to accomplish this task and I know that it is discouraged to create threads in an enterprise application.

So I started reading about worker manager and understood and tried a sample program in websphere application server 8.5.

I used asynchbeans.jar from websphere and now I am bothered that I am writing vendor specific code.

Then I came across commonj work api which is described in oracle java documentation. Now I am thinking to use commonj api from fabric3.

My doubt is, is there a better way to accomplish the same task? An EJB way? Or work manager is good for my requirement?

like image 200
Krishna Chaitanya Avatar asked Jan 14 '16 11:01

Krishna Chaitanya


2 Answers

You have some options:

  1. Asynchronous beans. These are vendor-specific, as you mention.
  2. commonj is just barely not vendor-specific. As far as I know, it was only implemented by IBM WebSphere Application Server and BEA WebLogic. The API was effectively superseded by Concurrency Utilities for Java EE, which is really the best choice.
  3. EJB @Asynchronous methods. Requires using EJBs (unwanted complexity for some).
  4. EJB timers. Requires using EJBs, requires serializable data.
  5. JMS. Probably requires using MDBs to receive the message, requires serializable data.
  6. Actually create threads. The EE specs do not recommend this, but as long as you don't attempt to use EE constructs (lookup("java:..."), JPA, UserTransaction, etc.), then you should be fine.
like image 50
Brett Kail Avatar answered Oct 08 '22 19:10

Brett Kail


JavaEE7 has the managed executor, that you can try. You can spawn a task with it, and recieve managed callbacks in a handler. This is part of EE standard and should be platform agnostic.

See JDoc here:

http://docs.oracle.com/javaee/7/api/javax/enterprise/concurrent/ManagedExecutorService.html

like image 39
Richard Tyregrim Avatar answered Oct 08 '22 19:10

Richard Tyregrim