Last Lombok Refactoring

This is the last refactoring example of deadlocked Java code using the “synchronized” keyword.

This example is from a site called Rose India.

I was not able to really use Lombok for this example. The classes that deadlocked extended Thread, and the only method in those classes was the run() method. I did not know if annotating run() with the Lombok annotation would work. The method run() was not marked with the “synchronized” method in the original. Instead there were two synchronized blocks in the run() method. The two classes were using the same String objects to lock, which is why there was a deadlock.

So I decided to do by hand what Lombok does behind the screens. I created a private final object in each method and used those for one of the locks. Just as in the other examples, the deadlock was broken.

Here is the original;

Here is the output of the original:

Here is the refactored version:

Here is the output of the refactored version:

 

Image from Wikipedia page for the Indonesian province of Central Java, assumed allowed under Fair Use.

Third Lombok Synchronized Example

Here is another installment of my exploration into concurrency in Java. I have written about finding the Lombok library which uses annotations to reduce boilerplate in Java code.

One of the annotations provided by Lombok is @Synchronized. It is to replace the “synchronized” keyword and prevent some of the problems that can come with using the “synchronized” keyword. There are other annotations available via Lombok, but I have not looked at them.

Here is the third example of a program with a deadlock using the “synchronized” keyword that I refactored with Lombok. I got this example from the Java 2S site.

For this one I have also included the output of each of the programs.

Here is the program:

Here is its output:

There is a line that says “Ending method main”, but it does not end unless you kill the program.

Here is the program refactored with Lombok:

Here is the output of the refactored program:

Image from the Wikipedia page for the Indonesian province of West Java, assumed allowed under Fair Use.

Second Lombok Synchronized Example

Here is the second example of a program that deadlocks, with an example that I refactored using the @Synchronized annotation from Project Lombok.

This example was posted on one of the LinkedIn groups in which I first started asking about concurrency using the synchronized keyword. The basic idea to prevent deadlock is to mark the methods with the @Synchronized annotation. For one of them you should create a private, final object, and use the name of that object as the element for that annotation. For the other method that deadlocks I just use the annotation without an element.

Here is the original that was posted:

Here is the version with the Lombok refactoring:

I have a couple more examples before I get to my notes from No Fluff Just Stuff.

 

Image from the Wikipedia page for the Indonesian province of West Java, assumed allowed under Fair Use.

 

 

First Lombok Synchronized Example

I found some examples of Java programs that become deadlocked due to their incorrect use of the “synchronized” keyword. I decided to try to get them to work using the @Synchronized annotation provided by Project Lombok.

First, here is the example from the Really Big Tutorial.

 

Here is the same program with Lombok:

I will have a few more examples over the next few days.

Image from the Wikipedia page for Jakarta, a province in Indonesia. With Java, the name is usually based on coffee or Indonesia. Image assumed allowed under Fair Use.

 

2012-01-11 Update

I have decided to learn other technologies during my job search. I applied to Code Academy here in Chicago. It is a 12-week program that teaches Ruby on Rails and entrepreneurship. I am also interested in Clojure and Android, but I decided that I needed to sign up for some training to give myself some focus.

The only Clojure training that I could find was only a week. I did not look for Android training. Code Academy is three months, and a lot of people in the Chicago technology and startup communities are involved to provide mentors, equipment and advice. I think that getting training of longer duration will be better because there is more time to absorb the material. Plus there are a LOT of people involved. I will still be jumping off a cliff at the end, but I think that the chance of success is a lot higher.

The current class is the second class to go through.

The original intent was to teach web technologies to entrepreneurs since a lot of startups fail since most founders do not know technology and do not always communicate well with their developers. Plus a lot of developers do not know much about being on the other side of the desk. I plan on staying a software developer, but I would like to know more about what makes founders, investors and VCs tick. A few people have suggested that I go freelance, but then I would have to deal with sales, and paperwork, and all the things that software developers do not like. What is the difference between an S-Corporation and an LLC? These will be covered in addition to Ruby on Rails.

There were also some people in the first class who were software developers who wanted to transition to Ruby on Rails. After speaking to a couple of them, I decided to apply. When I had the interview I also spoke to another developer transitioning to Ruby on Rails.

I will still be posting about Java. I am finally getting around to some posts about things that I have been thinking about for a while.

Lastly, to use some pseudo-Java notation,  “Code Academy” != “CodeCademy“.

Image from Code Academy, assumed allowed under Fair Use.

A Closer Look At Project Lombok

This is a continuation of my look into concurrency in Java.

I found a library called Lombok that uses annotations to reduce boilerplate code. Instead of using annotations for metadata, it uses hidden APIs to alter the class files. Some people do not like this because it is voodoo, but it seems to get the job done. There is a possibility that at some point in the future it will stop working.

For threading, it has an annotation @Synchronized. It has other annotations as well. The voodoo for the @Synchronized annotation is that it will create a private object and inject a synchronized object locking on the private object that it created. There is another version that takes a java.lang.String as a parameter (or element as they are called for annotations). If you use this version, then you provide the name of the object you want to lock on.

Here is what the javadoc says: “Almost exactly like putting the ‘synchronized’ keyword on a method, except will synchronize on a private internal Object, so that other code not under your control doesn’t meddle with your thread management by locking on your own instance.” So I suppose you could do everything that this annotation does for you by providing your own objects. But using Lombok makes your code a lot easier to read.

It would be great if every time you used the “synchronized” keyword the javac compiler created a unique object for that method or block.

In the discussions on LinkedIn, a few people have mentioned that using the synchronized keyword can cause performance issues. I do not know if creating and using a different object degrades performance. I got the impression from the discussions that the performance issue is due to applications repeatedly getting a lock on the same object. I have read that object creation is now cheap, so I do not think that using different private objects for locks would be that big of a deal.

But I do think that it helps prevent deadlocks. I got a few examples of deadlocks from the internet, including one from the Really Big Tutorial, and one from the LinkedIn discussions. I was able to refactor them with Lombok to prevent the deadlocks. I did have to use both forms of the @Synchronized annotation: One with the optional java.lang.String element, and one without. Only using the no-element annotation did not prevent the deadlock.

I will post the deadlock examples I found on the internet as well as my changes with Lombok.

Image from Wikipedia article about Mataram (city), the largest city on Lombok and the capital of the province containing Lombok, assumed allowed under Fair Use.

Immutable Objects

One thing I forgot to mention the last time is that someone suggested that if you still want have methods marked as synchronized you need declare them as final to avoid subclassing and deadlocks. One person suggested I take a look on ReentrantReadWriteLock’s which is good for synchronization and don’t have problems like ‘synchronized’ monitors.

In the LinkedIn discussions on the synchronized keyword, someone suggested using immutable objects. It is the easiest way to be thread-safe. One thing that bothers me about immutable objects (if “bothers” is the right word) is that you lose inheritance. Therefore you lose a lot of the benefits of using an object-oriented language.

One commenter responded that “object oriented” and thread-safety are very hard to combine in same application. An immutable class cannot be a real parent because only getters will work and you not able change internal state of objects. However, you can extend by adding new fields.

Another commenter wrote that you don’t lose inheritance, you lose mutable fields (hence inheritance of mutable fields). You can still inherit non-mutable values, and inherit or override methods. In this sense, object-orientation and parallel code mix perfectly well. It is possible, and actually pretty efficient, to write complex applications using only immutable objects (one example is Erlang, but you could do the same in Java with some discipline). It just requires a different state of mind when designing the code. Clean and maintainable code, and no locks required ever.

I thought you lose inheritance with immutable classes since most (nearly all of them in fact) tutorials/pages/articles on immutable classes say to declare immutable classes as final. But the Really Big Tutorial says that if you do not declare the class to be final that you should make the constructor private and create instances with a factory object.

A few good pages on immutable objects can be found here, here, here, here and here. There is also a presentation from Strange Loop by Josh Bennett here.

I also thought of another issue with immutable objects: web applications. Do any frameworks use immutable objects? Do the open source servlet engines use immutable objects under the hood?

Image from Wikimedia, assumed allowed under Fair Use. Image from the Vatican Virgil, a 5th century manuscript of poems by Virgil.

Concurrency Discussions on LinkedIn

Several months ago I mentioned that I posted a question about using the “synchronized” keyword for concurrency to a few LinkedIn groups. I recalled that a speaker at No Fluff Just Stuff said that a good rule of thumb is to declare your variables private, and to mark any methods that alter them with the “synchronized” keyword. I had heard that concurrency is complicated. Was the speaker’s advice too good to be true?

Perhaps. A lot of the responders said that if you synchronize a method, the JVM gets a lock on the object. This could cause deadlock if another thread also tries to call that method. Plus if you mark too many methods as synchronized then you could have performance issues, since the JVM has to acquire and release the same lock over and over.

Several responses suggested using synchronized blocks with a different object for each block. This would cause less contention and there would be less chance for deadlock. There was some debate whether there would be any performance hits due to locking. But deadlocks were mentioned quite a bit.

A few people suggested avoiding lock-based concurrency and to instead look at the java.util.concurrency packages.

Someone suggested I look at Brian Goetz’s book. Another poster pointed out that “Brian elaborates on it for good four hundred pages.”  Which is a reason to not read it. I keep thinking that something this important should be easier.

Image from Wikimedia, assumed allowed under Fair Use. Image from the Vatican Virgil, a 5th century manuscript of poems by Virgil.

2011-10-18 CJUG Meeting

Gradle: Bringing Engineering Back to Builds

By No Fluff Just Stuff speaker Tim Berglund

Gradle. Another build tool? Come on! But before you say that, take a look at the one you are already using.

Whether your current tool is Make, Rake, Ant, or Maven, Gradle has a lot to offer. It leverages a strong object model like Maven, but a mutable, not predetermined one. Gradle relies on a directed acyclic graph (DAG) lifecycle like Maven, but one that can be customized. Gradle offers imperative build scripting when you need it (like Ant), but declarative build approaches by default (like Maven). In short, Gradle believes that conventions are great — as long as they are headed in the same direction you need to go. When you need to customize something in your build, your build tool should facilitate that with a smile, not a slap in the face. And customizations should be in a low-ceremony language like Groovy. Is all this too much to ask?

Gradle has received the attention of major open source efforts and has chalked up significant conversions by the Spring Integration, Hibernate, and Grails projects. What do these technology leaders see in this bold new build tool? They see not only a better way to build Java applications, but an extensive ecosystem of connecting to existing Ant and Maven build files while expanding the horizon of test, CI, and deployment automation in an easy manner. Let us take you on this same walk of discovery of the most innovative build tool you’ve ever seen’.

The Speaker:

Tim Berglund is a full-stack generalist and passionate teacher who loves coding, presenting, and working with people. He has recently been exploring non-relational data stores, continuous deployment, and how software architecture should resemble an ant colony. His firm, the August Technology Group, helps clients with product development, technology consulting, and technology upgrade projects atop the JVM.

Tim is a speaker internationally and on the No Fluff Just Stuff tour in the United States, and is co-president of the Denver Open Source User Group in the Denver area, co-author of the DZone Clojure RefCard, co-presenter of the best-selling O’Reilly Git Master Class, and co-author of a forthcoming series of ebooks on the next-generation build system, Gradle.

We will also give away a ticket to the Great Lakes Software Symposium, the No Fluff Just Stuff conference that will happen in Chicago November 11-13.

Time: 6:00, October 18th, 2011
Place: CME
20 South Wacker Drive
ULL-A Auditorium
Chicago IL, 60606

Click here to RSVP. RSVPs will close on Tuesday, October 18th at noon.

CME Employees, please contact Joshua Bennett to RSVP.

Java Web Frameworks

We have had a couple of interesting presentations at CJUG in the past few months.

In July we had a presentation on Play, which seems to be getting some traction.

In August, we had Igor Polevoy from Productive Edge talk about is new framework ActiveWeb. Like Play, Rails and Grails, it is full-stack. Last year he gave a presentation on ActiveJDBC, an ORM framework he started based on ActiveRecord. The mailing list gets a few dozen posts a week, so it looks like there is an active community of users and developers for it. He said that his company has been using ActiveWeb for a few clients, including a couple of Fortune 500 firms.

First off, it is nice to see that there are some Java projects coming out of Chicago. It is also nice to see that there are some Java web frameworks that are striving for the ease of use and completeness of Rails and Grails.

Image from CJUG website, assumed allowed under Fair Use.