.connect{ follow ->

}

Understanding Immutable Classes In Java

I recently reviewed an article that claimed immutable classes in Java are not always thread safe. Ultimately, this is not true since any immutable class cannot contain state and therefore no two threads could change it's state.
To understand this more, I would like to do a quick dive into what an Immutable class is in Java.

Proerties of an immutable class in Java

In order for your class to be truly immutable, it must meet the following cirteria:
  1. All class members are declared final.
    • All variables used in a class at the class level must be instantiated when the class is constructed.
  2. No class variable can have a setter method.
    • This is implied from the first statement, but want to make it clear that you cannot change the state of the class.
  3. All child object must be immutable as well, or their state never changed in the immutable class.
    • If you have a class with mutable properties, you must lock it down. Declare it private, and ensure you never change it's state. More on this at the end.

In order for a class to be immutable it must be stateless. This means it's properties should never change once the class is initialized. Anything that can change state must be handled within the methods of the class.
Example Stateless Class:

public class ImmutablePair<I, J> {

    private final I first;
    private final J second;
    
    public ImmutablePair(I first, J second) {
        this.first = first;
        this.second = second;
    }
    
    public I getFirst(){
        return this.first;
    }
    
    public J getSecond(){
        return this.second;
    }
}

The Immutable class holds up it's end of the bargain. Any call into the class will never change the state of an instance. If one thread instantiates this class, and two threads begin using the object, there is no chance that they will get a different value for the pair on a call to getFirst() since neither can reset the values of the pair.

Yes, Immutable Means Thread Safe. It's that simple.

Plain and simple, IMMUTABLE IS ALWAYS THREAD SAFE, and it is a very simple concept. If somethings state cannot change upon instantiation, no two threads can ever write to the object and break it's state.

The other day I was curious what people thought about this topic. A top hit from DZone claimed not always, and I would like to rebuttal.

Here is a link. https://dzone.com/articles/do-immutability-really-means

And my response:

Yes Java claims that String is immutable. And yes, for all intensive purposes it is. What the writer happens upon is a special case, where a hash property IS MUTABLE.

 122       /** Cache the hash code for the string */
 123       private int hash; // Default to 0

So, the writer is correct that String hash attribute is mutable, and therefore String is not completely immutable. Also note that the Java team guarantees it's thread safety with the writing of it's hashCode() method as thread safe. By making it private they ensure the variable is inaccessible to users and therefore still thread safe.

He also shares an example where his class has it's fields declared final, but the property in his class can hold state.

public class VerySimpleDateFormat {

    private final DateFormat formatter = SimpleDateFormat.getDateInstance(SimpleDateFormat.SHORT);

    public String format(Date d){
        return formatter.format(d);
    }
}

This again, is not the definition of an immutable class. Your class is mutable, since you can change the state of it's properties, just not the direct reference.

Immutable implies thread safety. If a developer writes an Immutable API, we better trust it's claim, and if (for some special case), they have a mutable property in that class, they guarantee it's thread safety and that the property cannot be written to (marked private).

To learn a bit more on immutable classes see my later blog post on the topic.

Spring HATEOAS - Embedded Resources with HAL

One common issue I see on the web is people having trouble rendering their JSON objects in HAL with embedded resources. For this example I am using groovy, but it explains how to configure the rendering of resources in a spring applicaiton.

Rails Unfit for Microservices?

This is a relatively informal blog post. Looking more for feedback and response to get a conversation started. The prerequisite to this thread is that you have a fairly good understanding of Microservices. If not at least read the following link:
http://martinfowler.com/articles/microservices.html

The Java Enum: A Singleton Pattern


The singleton pattern restricts the instantiation of a class to one object. In Java, to enforce this, the best approach is to use an enum. This great idea comes straight from the book Effective Java by Joshua Bloch. If you don't have it in your library, get it. One of the best Java books to date.

There are a few reasons why one would use an enum as a singleton in Java:

Bootstrap Guide: The Virtual Tour Library

Introducing a Virtual Tour Library (using TW Bootstrap)


 A jQuery library used for designing help pages for your website. Gives the user a guided walk through of your webpage and it's functions.



Rails Associations: Always think of the user

The topic of discussion in this post is Rails associations. Primarily, we will be focusing on which association you should choose in certain advanced scenarios. If you understand Rails associations but want better insight on deciding which associations to use, then this post is for you.

Java Developers Need To Be Using Lombok


Lombok is a Java library meant to simplify the development of Java code writing. This article deals with writing classes that need getters/setters, override equals, hashCode, toString and/or offer a copy constructor. Way to go Java! You just made writing a simple class cumbersome. Project Lombok will make your day if you haven't seen it yet.

Adding Groovy Sources to Maven Build Path


Say you want to run a groovy class method from your Java project in Maven. You've placed the script file at src/main/groovy/script/MyGroovyScriptClass.groovy. In Java, you would load the class and execute its method like so:

Ignore Header and Trailer Lines During Java InputStream Read

Ignore first + last lines in a file

After beating my head against the wall for some time, I was finally able to come up with a solution for this.

Say you want to hand off an InputStream or InputStreamReader to an underlying API. The problem is that your input stream may have a header or trailer. Those header/trailers differ from the underlying format. This is commonly true for CSV, EDI, and fixed length file types. So if you want a CSV file parsed by a Java API like the Smooks api, you will need to hand the framework an InputStream.

Grails Part 5 - Adding Basic Security

Click here to view the full tutorial

Continuing series: Developing a Grails Web Application.
Tutorial will: walk through steps of creating a robust Grails web application.
Application name: grails-mongo-demo
The Goal: To track and record persons addresses.
This application will use the Grails Framework to develop a web application using:
1. MongoDB
2. Spring Security
3. Apache CXF
4. Jetty Web Server
5. Maven build integration => Removed upon Request
Previous Post: Grails Part 4 - Enhanced UI Design w/ tw Bootstrap
View Project on Github

These Instructions Will Walk Through:

  • Configuring Spring Security Plugin
  • Adding static URL maps
  • Bootstrapping in security data
  • SecurityTagLib - Conditionally display gsp content
  • Configure Security Pages with Twitter Bootstrap UI

Grails Part 4: Enhanced UI Design w/ Twitter Bootstrap

Click here to view the full tutorial
Continuing series: Developing a Grails Web Application.
This application will use the Grails Framework to develop a web application using:
1. MongoDB
2. Spring Security
3. Apache CXF
4. Jetty Web Server
5. Maven build integration => Removed upon Request
Previous Post: Grails Part 3 - Building a CRUD Application
View Project on Github

These Instructions Will Walk Through:

  • Enhanced UI Design with tw bootstrap
  • Configure Bootstrap with lesscss-resources plugin
  • Adding a custom controller
  • Customizing Scaffold Templates
  • Improving Scaffold Output

Grails Part 3 - Building a CRUD Application

Click here to view the full tutorial
Continuing series: Developing a Grails Web Application.
This application will use the Grails Framework to develop a web application using:
1. MongoDB
2. Spring Security
3. Apache CXF
4. Jetty Web Server
5. Maven build integration => Removed upon Request
Previous Post: Grails Part 2 - Configuring the Plugins
View Project on Github: Grails MongoDB Demo

These Instructions Will Walk Through:

  • Building a CRUD Application
    • Building the Domain Model
    • Controllers using Grails Scaffolding

Grails Part 2 - Configuring Web Application Plugins

Click here to view the full tutorial
Continuing series: Developing a Grails Web Application.
This application will use the Grails Framework to develop a web application using:
1. MongoDB
2. Spring Security
3. Apache CXF
4. Jetty Web Server
5. Maven build integration => Removed upon Request

Previous Post: Grails Part 1 - Setting up a Project on Maven With IntelliJ
View Project on Github: Grails MongoDB Demo

These Instructions Will Walk Through:

  • Configuring the Plugins
    • MongoDB
    • Jetty
    • Spring Security
    • Apache CXF (WSClient)

Grails Part 1 - Setting up a Project

Click here to view the full tutorial
Continuing series: Developing a Grails Web Application.
This application will use the Grails Framework to develop a web application using:
1. MongoDB
2. Spring Security
3. Apache CXF
4. Jetty Web Server
5. Maven build integration
View Project on Github: Grails MongoDB Demo
These Instructions Will Walk Through:
  • Installing the Grails SDK
  • Project Setup
    1. Creating a Grails Application
    2. Integrating with Maven
    3. Integrating with IntelliJ

Applying the Strategy Pattern in Java

Working with strategy on Arrays.sort & java.util.Comparator

All these examples and more can be found on github
In Java, you cannot pass function references through a method. With this being true, how do we then apply a strategy to a method? What is suggested, is that we define an interface with the function we want to pass. This way we can on the fly, define and pass an algorithm to a method for process.

In this demo, we will be working strictly with the strategy interface: java.util.Comparator. This is a java strategy interface, readily available in the Java API as of 1.5. It supplies a compare algorithm, where its implementation is primarily for sorting large collections of objects.

Atmosphere Websockets & Comet with Spring MVC

Since writing this guide, Spring has come out with their own Comet and Websocket implementations. I suggest you first read through their guides before deciding on atmosphere as your Comet & Websocket solution.

1. Messaging with Stomp over Websockets
2. Spring Messaging

On to the guide...

Feel free to clone the source of this project on github.
springMVC-atmosphere-comet-websockets

The Websocket protocol is defined by W3C here. The protocol is considered an HTTP upgrade protocol. Essentially what happens is, a websocket request is made by a client browser, via the HTTP protocol. Once, the request is in, the server should respond with a success. Then the browser and server establish a TCP link to handle communication from there on out. This protocol enables bi-directional communication between a client and server. Here is a link to browser and servers that support Websockets and/or Comet: comet/websocket support link