Const Correctness in Java

I started re-reading the old standby Java Concurrency in Practice to refresh some of the foundational concepts of Java multi-threading.  Early in the book, there is a section proposing the strategy of designing immutable objects in order to reduce or eliminate the likelihood of all the crazy things that can happen in the Java multi-threaded universe, such as seeing stale values, losing updates or seeing objects in an inconsistent state and I was once again struck with the thought of how much easier it would be to implement this approach if Java supported a C++ like mechanism of “const correctness“.

Figuring I was not the only person to have this thought, I went to StackOverflow to see what others had to say about this, and I must admit I was disappointed with the quality of the discussions.  I felt like many of the posters did not have a good understanding of the C++ mechanism and so their arguments were not convincing.  I did find a link to the proposal which was made to Sun in 1999 to add the const mechanism to Java and the documented reasons for the rejection of that proposal.  Looking at it now in retrospect, the reasons don’t seem very convincing.  I am listing them below so you can judge for yourselves.  The line about “creeping featurism” seems especially ironic, given how much “features” have been added to Java in the past decades.  In the words of our new President-elect – “Sad!”

It's possible, but I would rather hold the line on creaping featurism. One can
design around this (using interfaces, wrappers etc.).

gilad.bracha@eng 1999-12-22

There are no current plans to add this feature to Java.  In
addition to creeping featurism, we see the following problems
with this feature:

* Adding const is too late now.  Had this been added from 1.0,
  the situation could have been different.

* Const pollution: the C++ approach requires all const methods
  to be marked with a const keyword.  This means that most
  methods will have to be marked const explicitly.  This tend
  to clutter all methods in C++.

* Compatibility is a very important feature of the JDK.
  Arguably, the collection classes should be modified to
  indicate that the elements are const.  That would
  require all existing implementations to be updated in
  the same way, effectively breaking all existing non-JDK
  implementations of the collection interfaces.  Similarly,
  hashCode would have to be const, breaking the current
  implementation of String.