Over a million developers have joined DZone.

Legally Starting Threads/Synchronizing EJBs - Hell Or Heaven

· Java Zone

Microservices! They are everywhere, or at least, the term is. When should you use a microservice architecture? What factors should be considered when making that decision? Do the benefits outweigh the costs? Why is everyone so excited about them, anyway?  Brought to you in partnership with IBM.

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

Discover how the Watson team is further developing SDKs in Java, Node.js, Python, iOS, and Android to access these services and make programming easy. Brought to you in partnership with IBM.


Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

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