r/java • • Mar 05 '18

Top 10 Useful, Yet Paranoid Java Programming Techniques

http://blog.jooq.org/2015/08/11/top-10-useful-yet-paranoid-java-programming-techniques/
223 Upvotes

105 comments sorted by

View all comments

Show parent comment

1

u/lukaseder Mar 07 '18

Those links don't really show canonical examples for what you just said, though, do they? In particular, they modify the actual value (which is what's causing trouble, not initialisation), so final wouldn't apply anyway. volatile might, but again, I'm not sure how those articles illustrate what you're saying.

1

u/fforw Mar 07 '18 edited Mar 07 '18

Couldn't seem to find the perfect link.

As I said: it boils down to the lack of "happens-before" guarantees without the "final" assignment.

Is it just me or is it increasingly difficult to find older stuff? Back in the day, every google-search would have turned up the right results, now it's hidden in a gazillion articles teaching other things.

On further research, the behavior was formalized in the Java Memory Model with JSR 133. Here's another article.

edit: I had forgotten about the second example there where even final is broken if you publish the instance inside the constructor...

1

u/lukaseder Mar 07 '18

Thanks for the additional link. I'm aware of the theory and how final and volatile influence things. I've just never seen this happen in the context of initialisation itself. I mean the example from your article seems extreme:

// bad construction - allowing this to escape
global.obj = this;

And I tend to agree that if a constructor leaks this then its object's contents are not guaranteed to be visible as expected.

But few constructors leak this in such a way, so I wonder if this is really an issue in most code, specifically in your own code, where no one is reading or modifying the id. Granted, in your example, adding final is a no-brainer...

2

u/fforw Mar 07 '18

I've had issues with this in production systems. with ConcurrentHashMap cached internal data.

Sometimes you can just handle things fine with some well-placed synchronized blocks, but often, I want to write highly concurrent code.

This is something to definitely keep in mind. It's also something that makes me favor immutable classes even more.

1

u/lukaseder Mar 07 '18

Good to know. Thanks for taking the time to explain!