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.


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.

Looking at Project Lombok

My look into concurrency continues. I am messing around with some of the comments that I have gotten from my posts on LinkedIn and Stack Overflow.

I also found a project called Lombok, named after one of the islands of Indonesia. It uses annotations to replace a lot of boilerplate in Java for a few tasks, including threading. It can handle getters and setters, equals and hashCode and logging as well as synchronization.

A few of the forums that I have been on have recommended looking at something other than the “synchronized” keyword, which Lombok seems to rely on. But it is still worth looking at.

Image from the Wikipedia page for West Nusa Tenggara, the Indonesian province which contains Lombok, assumed allowed under Fair Use.

Update On Concurrency

I still plan on posting more on concurrency. I made a small Java app to test out a few ideas.

Some of the discussions on Linked In had died down, but there were a lot of replies in the past few days. I am getting some contradictory advice. It seems like the more I read the more complicated it gets. This is making Actors look more appealing.

Do all languages have multiple ways of approaching concurrency, or just Java? It seems like other languages don’t deal with this stuff. I am surprised there are not three Thread pool wrapper libraries at Usually they solve a problem in Java three ways.

Image from Wikimedia, assumed allowed under Fair Use.


Update on Concurrency

I posted my last post in a few LinkedIn groups. I got a few responses, some of which have led me to more questions. So I may post some follow up questions. Then I will try a few more of the groups.

In one of the groups it got deleted. I have no idea why.

I also got a link from one of my Twitter followers (a lovely young woman in Tunisia) to an article about GPars, an Actor library that can be used from Groovy or Java. I will look into that at some point.

First Concurrency Technique

In November 2009 I went to No Fluff Just Stuff. One of the presentations was by Brian Goetz, which was about Java concurrency. For some reason there were items on his agenda slide that were not covered in his presentation.

He went over some strategies, and at the end he pointed out a common tactic that he also said is a good rule of thumb for concurrency in Java: Make your variables private, and make any methods that access them synchronized.

That sounds pretty simple. And perhaps too good to be true. I will post on some forums and boards populated by people with more knowledge than me if there are situations/applications where this concurrency technique would not be sufficient. Would relying primarily on this technique work well in systems with lots of transactions, or large data sets? What are the potential drawbacks of doing this?

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

Posts About Concurrency

I have decided to make some posts about Concurrency.

One of the gaps in my Java knowledge is concurrency. I think I have lost a few job opportunities due to my lack of concurrency knowledge. (There are a lot of trading firms here in Chicago.)  Sometimes I think concurrency is also Java’s Achilles’ Heel as well as my own.

I have noticed on some Linked In groups and forums that a lot of managers and recruiters have said it is hard to find Java developers with good concurrency knowledge. The reason is that a lot of Java developers make web apps, and they let the application servers and servlet containers handle concurrency. Part of me thinks is the smart way to go. Threading is hard. The JVM handles memory for you; why not let something handle threading for you?

Anyway, I think I have learned a few things about concurrency. So I will write a few posts about what I know. I will look at some techniques, libraries and languages.

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