Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Concurrency - Publishing Immutable Objects (Java Concurrency In Practice)

In Java Concurrency In Practice, the author stated that

  1. Immutable objects can be published through any mechanism
  2. Immutable objects can be used safely by any thread without additional synchronization, even when synchronization is not used to publish them.

Does it mean that the following idioms are safe to publish immutable objects?

public static List<ImmutableObject> list = new ArrayList<ImmutableObject>();

// thread A invokes this method first
public static void methodA () {
    list.add(new ImmutableObject());
}

// thread B invokes this method later
public static ImmutableObject methodB () {
    return list.get(0);
}

Would there be any data race? (which means thread B may not be able to see the Immutable Object in the list added by thread A)

Thank you very much.


More, the author said that the following code is safe if Resource is immutable.

@NotThreadSafe
public class UnsafeLazyInitialization {
    private static Resource resource;

    public static Resource getInstance() {
        if (resource == null)
            resource = new Resource();  // unsafe publication
        return resource;
    }
}

Section16.3 The guarantee of initialization safety allows properly constructed immutable objects to be safely shared across threads without synchronization, regardless of how they are published even if published using a data race. (This means that unsafeLazyInitialization is actually safe if Resource is immutable.)

For the 2nd part of this question, it is discussed in detail in another question (click here)

like image 308
ben ben Avatar asked Jan 31 '26 19:01

ben ben


1 Answers

Yes, you are correct, there is a data race.

Only the ImmutableObject is immutable and can be shared safely between threads, your List, however, does not have these same guarantees, so there is a data race between adding the ImmutableObject and retrieving it.

In JCIP, the authors meant immutable objects are safe to publish in the sense that you don't have to worry about doing things like making defensive copies.

As to:

Immutable objects can be used safely by any thread without additional synchronization, even when synchronization is not used to publish them.

This statement means that given 2 threads with an immutable object A that they both acquired through any means, they can both use object A without worrying about thread-safety issues.

like image 56
Alex DiCarlo Avatar answered Feb 03 '26 07:02

Alex DiCarlo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!