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.