Coding the Thread Deadlock


You want a deadlock right?

I wanted to make sure that I understand this correctly. Thread deadlocks are one of the issues that Core Java Developers usually faced especially if developing a high availability/performance application. They need to ensure that threads are created in an efficient manner.

I’d like to disclaim that I’m an expert on the subject matter, but I do understand why it can happen, how to identify and how can it be resolved.

Take a look at an threadlock example below:

package com.areyes.datastruct;

class Friend {
	private final String name;

	public Friend(String name) {
		this.name = name;
	}

	public String getName() {
		return this.name;
	}

	public synchronized void bow(Friend bower) {
		System.out.format("%s: %s" + "  has bowed to me!%n", this.name,
				bower.getName());
		bower.bowBack(this);
	}

	public synchronized void bowBack(Friend bower) {
		System.out.format("%s: %s" + " has bowed back to me!%n", this.name,
				bower.getName());
	}
}

public class DeadLock {
	public static void main(String[] args) {
		final Friend alphonse = new Friend("Alphonse");
		final Friend gaston = new Friend("Gaston");
		new Thread(new Runnable() {
			public void run() {
				alphonse.bow(gaston);
			}
		}).start();
		new Thread(new Runnable() {
			public void run() {
				gaston.bow(alphonse);
			}
		}).start();
	}
}

“What is deadlock?” answer is simple, when two or more threads waiting for each other to release lock and get stuck for infinite time , situation is called deadlock . it will only happen in case of multitasking.

“How do you detect deadlock in Java?” – easy as checking and testing your code. You can also check your systems thread dump and see from there if it’s in a deadlock.

Hope this helps!

Java 7 try-with-resources statement


In Java 7 you can write the code from the example above using the try-with-resource construct like this:

Screenshot at May 11 23-48-08

This is the try-with-resources construct. The FileInputStream variable is declared inside the parentheses after the trykeyword. Additionally, a FileInputStream is instantiated and assigned to the variable. When the try block finishes the FileInputStream will be closed automatically. This is possible because FileInputStreamimplements the Java interface java.lang.AutoCloseable. All classes implementing this interface can be used inside the try-with-resources construct. If an exception is thrown both from inside the try-with-resources block, and when the FileInputStream is closed (when close() is called), the exception thrown inside the try block is thrown to the outside world. The exception thrown when the FileInputStream was closed is suppressed. This is opposite of what happens in the example first in this text, using the old style exception handling (closing the resources in the finally block).

Reference: http://examples.javacodegeeks.com/core-java/java-7-try-resources-statement/

Basic Injection / Qualifiers, Scope


This is a continuation of the DI/CDI Basics tackled last week  – in this post, I’ll be discussing Basic Injection, Qualifiers and Scope.

In our last topic, there we’re a great deal of information regarding the concepts of DI/CDI, we also discussed how these beans or class loaded using the annotations  -that makes up the composition of the object and created samples on how can we declare them programmatically. In this post, we will tackle more on the injection part, e.i how to acquire a certain resource and inject them on another resource for usage.

So how to inject a bean in the first place?

Basic Injection

How do you inject a Bean?

  • Use @Inject <Java-Type> <variable> for field injection
  • <Java-Type> can be Java class or Java interface
public class MyGreeter {
   // Inject Greeting object for field injection
   @Inject Greeting greeting;
   public sayGreeting(String name){
      // You can then used the injected Greeting object
      System.out.println(greeting.greet(name)); 
   }
}

Where can beans be injected?

Bean can be injected at “Injection points”

  • Field
  • Method parameter

Method can be:

  • Constructor (useful for created immutable object) > Initializer
  • Setter method
  • Producer
  • Observer
public class MyGreeter {
   private Greeting greeting;
   // Use constructor method injection
   @Inject
   public MyGreeter(Greeting greeting) {
      this.greeting = greeting; 
   }
   public sayGreeting(String name){
      System.out.println(greeting.greet(name)); 
   }
}

Qualifiers

Qualifiers are used to assign a specific bean if there are multiple implementation type (interface and child classes). Say you have two candidates (implementation class) for a specific interface:

  • Interface is Person
  • Class 1 is Regular Person
  • Class 2 is NonRegular Person

c_diagram_person

We can use Qualifiers to cleanly designate the implementation of classes by introducing / creating an Qualifier annotation of your own:

RegularPerson Qualifier Annotation:

p_qualifier

NonRegularPerson Qualifier Annotation:

non_reg_qualifier

Now we need to create an implementation class and tag it to the Qualifier we created.

RegularPersonImpl:

regular_impl

NonRegularPersonImpl:

non_reg_impl

Note: You can have as many qualifiers as possible – remember that Qualifiers are meant to separate logical objects implementation from its common interface.

Now that the implementation is set, we can now Inject the class and use its qualifier.

implIn this example, you can clearly see the usage, by introducing a Qualifier, developer can clearly specify the implementation type by annotation.

Download the example here.

Other things you can do with Qualifiers?

I won’t be discussing further what else can you do with qualifiers, instead, I’ll give let you check this examples for you to try and explore:

Scope

Why in the first place we need Scope on our Objects? –  For Web applications, we need our beans to hold state over the duration of the user’s interaction with the application, for example, across multiple requests to the server.

There are 5 types of scopes that developers can assign to an object:

  • @Dependent (default)
    • The default scope if none is specified; it means that an object exists to serve exactly one client (bean) and has the same lifecycle as that client (bean).
  • @RequestScoped
    • State of an object is maintained during a user’s interaction with web application in a single HTTP request.
  • @SessionScoped
    • State of an object is maintained during user’s interaction with a web application across multiple HTTP requests.
  • @ApplicationScoped
    • Shared state across all users’ interactions with a web application.
  • @ConversationScoped
    • Conversation context is demarcated explicitly by the application
      • Spans multiple requests
      • But “Smaller” than session
    • Used when you want to have explicit boundaries of multiple conversations within a single session

I won’t be diving into the details here but what I’ll provide you are actual examples that you can run. Download the projects here.

Next Stop: DI / CDI – Advance

With this new features, you can clearly observe and imagine how it will improve developer productivity by simplifying a lot of processes to setup a Web Application – Qualifiers can be created to clearly separate logical / business beans with a common goal (by interface), scoping let developers control the flow and manage the state of objects – and the simplification of calling beans directly from the UI thru EL makes it more straightforward.

Please do check the samples and try them on your own, it would be better to check an actual example than by just reading thru the details and concepts. Enjoy!

DI / CDI – Basics


Introduction (DI/CDI Basics)

First of all, I would assume there is a bit of confusion to this, but the truth of the matter is, they are just the same – the difference is that usage and its purpose.

DI (Dependency Injection) is the general term  – this feature is basically the one doing the bean discovery and bean wiring process on any application. Its not just you use it in your application, you can also use it in your unit tests and mocks. Of course, there are a lot of DI frameworks out there, you have: Guice, Seam, Spring (Seam and Spring extended the DI scheme and made their own), EJB 3.x and CDI itself.

CDI on the other hand, combines all this technology and introduce a lifecycle to the components – this allowed unification of DI technologies to making development of new features straight forward and mostly doable; you can combine Seams lifecycle mappings with Spring MVC with JPA as its persistence layer – these technologies were all created separately yet with CDI, application developers can combine them to create and development JEE application.

I will need to break down the topics as I would definitely bore everyone with words and letters here so:

  1. DI / CDI Basics
  2. Basic Injection
  3. Qualifiers, Scope
  4. DI / CDI Advance

I will be creating separate posts for each!

Lets Begin! 

SPI (Service Programming Interface)

It also has this so called SPI – apparently a feature set along with API, but has a different purpose entirely.

  • The API is the description of classes/interfaces/methods/… that you call and use to achieve a goal.
  • The SPI is the description of classes/interfaces/methods/… that you extend and implement to achieve a goal.

With SPI, you can actually extend the JEE6 to create a different framework of your own, showcasing portability, and extensibility. (But I’ll dive into that later).

Why CDI for JEE6?

CDI has been around in JEE5 (J2EE) and has been a major success. A lot of new development benefits from its approach that ultimately simplifies the overall development process. Several reasons why CDI was improved in JEE6.

  • JEE5 do support resource injection, but it still lacks a general purpose dependency – it only supports @EJB, @PersistenceContext, @PersistenceUnit, @Resources) – of course this is with the exception of Spring that introduce different annotations for managing bean lifecycle
  • Non-type based injection (and weak)  – String name and XML injection is really fragile. Improving type-based injetcion enables better tooling in general.

Terminology

CDI – Context and Dependency Injection

Weld

  • JSR 299 reference implementation – reference implementation is the SPI used to etxend a JSR specific implementation.
  • Provides extended CDI support for Servlet Container.
  • CDI enhancements for extension writers.
  • Maven Archetypes for CDI and Java EE (I love maven!).

CDI Theme: Loose Coupling and Strong Typed

Loose coupling simply means objects is loosely independent to the objects that uses or currently using them. CDI introduces new features for decoupling such as qualifiers, enhances interceptors, decorators, message producer, consumer and its underlying events mechanisms. Will dive further in to each example on the advance topic of CDI.

Strong Typing – simply means that strict declaration of beans by letting the container create and map specific names to objects. This eliminates the need to do string based naming of beans, casting almost not needed since the casting is done by the container (by taking advantage of qualifiers).

Bean (What is it?)

There are technically many form of beans, you have: JSF Bean, EJB Bean, Spring, Seam, Guice CDI, Entity Beans, etc – but ultimately, beans are just POJOs that has special definition – definition that was defined by the Managed Bean 1.0 – specification made in Java EE6. What does this mean is that any POJOs can be any type of bean, as long as it complies with the specification standards – further simplifying the declaration and development process. The container does the work for managing the POJOs and will add support for it by giving / introducing common basic services such as:

  • Lifecycle Management (@PostConstruct, @PreDestory)
  • Injection of a resource (@Resource)
  • Interceptor (@Interceptors, @ArounInvoke)
@javax.annotation.ManagedBean
public class MyPojo {

@Resource   // Resource injection
private Datasource ds;

@PostConstruct  // Life-cycle
private void init() {
   ....
}  
@Interceptors(LoggingInterceptor.class)
   public void myMethod() {...}
}

With this in mind, what about EJBs, RESTs and CDI beans?

  • EJB bean service – managed bean, with the common services (above) and support for Transaction, security, thread safety and persistence.
  • REST bean service – managed bean with HTTP support
  • CDI bean – managed bean with lifecycle supports:
    • Auto discovery
    • Qualifiers
    • Scope
    • EL
    • Interceptors and Decorators
    • Alternative bean (by Qualifiers at runtime)

To put it into perspective, Manage Bean is ultimately an SPI that was extended for specific use. EJBs, Rest, Entity beans are all Managed Beans – but with additional services from the container. Thus, if you define a POJO with a @Stateless or @Stateful annotation, the container automatically detects that its an EJB bean and it needs container specific support like transactions, security, thread safety, extensions etc.

package mypackage;
import javax.ejb.Stateless;

@Stateless
public class GreetingBean {
  public String greet(String name){
      return "Hello " + name;
   }
}

A simple POJO class turned into a Stateless bean with just a flick of finger (actually typed in) that resulted to that one liner @Stateless code. Unlike how EJB was defined on the priori 3.x (such a pain).

Download the sample (above) from here: Click me

Automatic Bean Discovery

The CDI container is the one responsible for how the beans are discovered, but how does it do it?

  1. It first scan the classpath that contains both application and container archives.
    1. It tries to scan through the classpath and see what POJOs are tag for discovery – that is, Managed Bean. You can think of it that it puts in a pool and can readily available when another Managed Bean calls it thru injection (more on that on next blog topic)
  2. Then it detects presence of beans.xml (or any context xml file definition).
    1. For Spring fans, this is much like an applicationContext.xml (at least thats the convention, but loose) – you pass that xml on the contextConfiguration listener (thru parameter) and Spring CDI Container will automatically tag objects (beans) in it for discovery – of course you need to define scanning mechanisms (component-scan).

Ultimately, DI / CDI was introduce to simplify the development process, unify the technologies and overall to produce a more robust, extendible application. Letting all the container do the work in terms of tagging the common services of the bean makes the developer task easier and more over avoiding pitfalls as a result of previous frameworks. SPI – is really the definition of improvement here, allowing the actually JEE6 framework to be extendible creates a more dynamic nature – business application architects can now design their own framework and conventions. Put more business specific designs or annotations for their own rules and give the robustness and flexibility that is always required for enterprise application.

Next Topic: Basic Injection – I don’t want to put everything in one post, so I’ll leave it up to you to absorb first and check the sample I created. From here on now, I’ll tackle more on the examples of DI and CDI.

A Brief Overview of JEE6


J2EE has come a long way since its birth. It has evolve to a sub-par platform to an all globally renowned standard. Now, JEE6 the latest major specification for JEE platform has gone leaps and bounds to further enhance its capabilities as well as introduce more effective and efficient specs on the developers table, without compromising the standard capability that makes Java Web Applications durability stands on the tests of time.

javaee6_overview_short__1_.pdf__page_2_of_9_

Major Features of JEE6 – Though as a developer, what did change and how?

Right sizing: Profiles and Pruning

By introducing Profiles – technical architects / developers can control the APIs / Specs needed for the application. Java / JEE is a huge platform and imports a lot of apis to projects. Profiles is an introductory concept to limit the number of APIs needed for a specific application. For example: In a Web Application  (Web Profile), you need support for JSP, EL, JSTL, JSF, EJBs (backend) etc. This wouldn’t be the same APIs and SPECs for J2ME right or J2SE apps right? You wouldn’t need JSP support if you’re developing a desktop application or EL if you’r developing a J2ME app. The mission behind profile is use only what is necessary to build the application to optimally create and develop the implementation. One good pre-defined profile is the Web Profile that uses EJB Lite – trimmed down version of Enterprise Java Beans.

javaee6_overview_short__1_.pdf__page_5_of_9_

Pruning – is another feature for right sizing, allows removal of existing APIs or Frameworks being used by the application.  It provides a way to remove the following technologies from the platform.

  • Java EE technologies that are outdated and have been replaced by new sets of technologies
  • Technologies that are not well supported
  • Technologies that are not widely deployed

Extensibility – Plug-ability

Need other frameworks for your application? JEE6 has this plug-ability feature that will help developers ease their process of plugging in multiple frameworks to be used in their applications.  Not only its easy programmatically, doing so using Maven will ease it even more – by dependency management.

This mechanism provides a way to include additional technologies and frameworks that are not part of the standard platform. Extensibility points and Service Provider Interfaces (SPIs) help developers plug in these technologies to their platform implementations. Two new extensibility options are support for open-source enterprise application frameworks and scripting languages.

Ease of Development

Defaults over configuration – Profiles are set – why configure everything if there are pre-defined profiles that can be used? Idea: How about combining that with Maven Archetypes?

DI/CDI – Of course Spring is the master of Dependency Injection – but we’re in the open world, anyone can get the idea, create a new one an innovate it. Dependency Injection allows developers to class load POJOs using a one liner annotations. IoC scheme then uses these beans to inject them on any beans that are class loaded.

Specifications

The specs has come a long way, but the very foundation is still there. The more the specs improves, the better Java Development / JEE Development experience will be. After all the purpose of this specification is to simplify the things and stuff that works.

javaee6_overview_short__1_.pdf__page_8_of_9_

In this blog post, I showed the basics and powerful new features of JEE6 – next post, I’ll focus more on Servlets 3.0 and how it compliments or add up to the new platform.

Next Stop: Servlet 3.0 Basics!