0

Are transient objects safe from double-checked locking?

private transient java.lang.ThreadLocal __hashHistory;
public int hashCode() {
    if (__hashHistory == null) {
        synchronized (this) {
            if (__hashHistory == null) {
                __hashHistory = new java.lang.ThreadLocal();
            }
        }
    }

Or does the object need to be volatile?

Zibbobz
  • 725
  • 1
  • 15
  • 41
  • 1
    I don't see how a transient variable is relevant to double checked locking. If double checked locking is applied i believe volatile is just an overhead as you will implement a synchronized block. So answer is a private variable with out any modifier is sufficient. – Rami Del Toro Sep 05 '14 at 19:51
  • The reason I thought it might be related is because our previous fortification reported no double-checked locking issues, and I know this code was in place during that fortification. So either the previous person to fortify the code found some reason not to bother with fixing the double-checked locking problem, or they didn't realize it was a problem at the time/it wasn't recognized as a problem back when that fortification took place (Roughly 6 years ago). – Zibbobz Sep 05 '14 at 20:01
  • Perhaps the transient keyword was placed there for serialization purposes, this will not effect in any way the double-checked locking process. – Rami Del Toro Sep 05 '14 at 20:07
  • 1
    @RamiStefanidis The `synchronized` block is not enough without `volatile`. Read this: http://jeremymanson.blogspot.com/2008/05/double-checked-locking.html – David Conrad Sep 05 '14 at 20:26

2 Answers2

3

transient means that the field should be ignored during serialization. This keyword has nothing to do with thread locking so everything stays as safe or unsafe as it would be without it. I am not sure if volatile would be helpful either.

In your code, if __hashHistory == null, the two threads may approach the synchronized statement at the same time. They will pass the body of synchronized statement one by one, but still the two ThreadLocal's will be created. This is why double checked locking is considered anti-pattern: it is very difficult to get it right.

Audrius Meškauskas
  • 20,936
  • 12
  • 75
  • 93
  • 1
    It would work with `volatile` under the "new" memory model. The only problem with the code would be synchronizing on a publicly visible object. – biziclop Sep 05 '14 at 19:55
1

Transient has nothing to do with thread safety. The transient key word relates to serialisation. http://en.wikibooks.org/wiki/Java_Programming/Keywords/transient

Volatile only ensures that you are reading the global value of a field rather than a local thread cached value. It does not make any guarantees about whether that field will remain the same between one instruction to the next. So you must double check.

Dunes
  • 37,291
  • 7
  • 81
  • 97