I have an immutable object that doesn’t have its fields or class marked as final. I could do this, but is there really any benefit to doing this? I could see it saving the compiler a little bit of time figuring things out, but I can’t see it being “worth” it (other then the fact that it will make future developers rethink doing something to the object to make it mutable).
Share
Apart from the points you make (future developer modifying the fields being a very sensible one, another one is that someone could subclass your class and make it mutable), explicitly marking the fields as final provides you with visibility guarantees in a multi threaded environment.
Take this class – it is effectively immutable:
In a multi-threaded environment, it is possible that a thread T1 creates a
SomeClass sc = new SomeClass(1);and that another thread T2 readssc.getI()and sees 0.If
iis made final, this can not happen any more (assuming you don’t letthisescape during construction, as explained in the quote below).Reference: JLS #17.5 – emphasis mine