I am experimenting with scoped values, oracle JDK 20 on windows and eclipse 2023-03. From what I've read ScopedValues are supposed to be immutable, but they do not appear so in my test code
package demoJava20;
import jdk.incubator.concurrent.ScopedValue;
class User { String name; };
public class ExampleScopedValues {
public final static ScopedValue<User> LOGGED_IN_USER = ScopedValue.newInstance();
public static void main(String[] args) {
User loggedInUser = new User(); loggedInUser.name = "ABC";
ScopedValue.where(LOGGED_IN_USER, loggedInUser, () -> f1()); // value will be available through f1
}
private static void f1() {
User user = LOGGED_IN_USER.get();
System.out.println("In f1 user = " + user.name);
user.name = "DEF";
f2();
}
private static void f2() {
User user = LOGGED_IN_USER.get();
System.out.println("In f2 user = " + user.name);
}
}
On my machine this prints
In f1 user = ABC
In f2 user = DEF
This code looks like it successfully changes the value from ABC to DEF and f2 sees the changed value.
Is it just the object reference that is immutable ( by not having a set method ), not the object itself?
Yes,
user
is immutable, but as you and @Brian Goetz noted, you can still mutate the propertyname
.