Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Singleton Pattern in Java EE

DZone's Guide to

Singleton Pattern in Java EE

· Java Zone
Free Resource

Learn how to troubleshoot and diagnose some of the most common performance issues in Java today. Brought to you in partnership with AppDynamics.

The singleton pattern is one of the most well known design patterns and is used extensively by frameworks such as Spring. Java EE offers an elegant and easy way to implement the singleton pattern. By adding the @Singleton annotation to a class you can turn it into a singleton bean as shown in the following code snippet.

@Singleton
public class SingletonBean {

  public String message(){
      return "Hello Singleton World!";
  }

}
It is important to note that Java EE initialises singleton beans lazily unless annotated with @Startup.

We still have a potential problem with concurrency related method access. Java EE solves this issue rather simply with another set of annotations. By default the container manages concurrency, so an annotation is only required if you want to manage it yourself. This is called bean managed concurrency and is annotated on the class as in the following code snippet.

@ConcurrencyManagement(ConcurrencyManagementType.BEAN)
@Singleton
public class SingletonBean {

  @Lock(LockType.READ)
  public String getName(){
      return "Return name from Cache";
  }

  @Lock(LockType.WRITE)
  public void addName(String){
      // code that adds name to cache
  }

}
Further annotations are necessary when this option is chosen. We control access using the familiar read/write concept and annotate methods appropriately as can be seen in the above example.

If you are interested in learning more about how we can develop singletons in ways there were never possible before I suggest that you read chapter 4 of my book Professional Java EE Design Patterns.

Understand the needs and benefits around implementing the right monitoring solution for a growing containerized market. Brought to you in partnership with AppDynamics.

Topics:

Published at DZone with permission of Alex Theedom. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

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.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}