Over a million developers have joined DZone.

Legally Starting Threads/Synchronizing EJBs - Hell Or Heaven

DZone's Guide to

Legally Starting Threads/Synchronizing EJBs - Hell Or Heaven

· Java Zone
Free Resource

What every Java engineer should know about microservices: Reactive Microservices Architecture.  Brought to you in partnership with Lightbend.

EJB spec does not allow starting and managing threads ...in general. With @Singleton you can do whatever you want even:

With Bean Managed Concurrency demarcation, the container allows full concurrent access to the Singleton bean instance. It is the responsibility of the bean developer to guard its state as necessary against synchronization errors due to concurrent access. The bean developer is permitted to use the Java language level synchronization primitives such as synchronized and volatile for this purpose. [EJB 3.1 spec, page 111]

You only need to apply an additional annotation on a @Singleton and do whatever you want - at least synchronization-wise:

public class InefficientHelloWorld {
//AtomicInteger would be a lot better.
private static volatile int counter = 0;
//synchronized just for demo purposes, o.k with CMT.Bean.
public synchronized void sayHello(){
new Thread(new Runnable() { //still not allowed - but it works
public void run() {
//out.println is not a best practice either...
System.out.println("Hello World: " + counter++);


In the majority of all cases it is better to use just @Stateless beans and just let the container manage threads and synchronization for you.
@Asynchronous is far better and easier to use , than the example above.
The "working" example was pushed into http://kenai.com/projects/javaee-patterns/. The name of the project is "BeanManagedConcurrency". Starting and managing threads in the application code is hard to implement, monitor and debug - it is by no means a best practice. [See Lightweight Asynchronous Facade pattern, page 65 in "Real World Java EE Patterns Rethinking Best Practices" book for more in-depth discussion] 

From http://www.adam-bien.com

Microservices for Java, explained. Revitalize your legacy systems (and your career) with Reactive Microservices Architecture, a free O'Reilly book. Brought to you in partnership with Lightbend.


Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}