0

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?

Gonen I
  • 5,576
  • 1
  • 29
  • 60
  • This seems like a self-answering/ed question. – Dave Newton May 17 '23 at 16:07
  • 4
    You are confusing mutability of an object reference with mutability of the object it refers to. If you took scoped values out of the equation, you could have `final User u = new User(...)` and then still mutate `u.name`. Here, `final` applies to the reference, but the object can still have mutable state. Same with scoped values. – Brian Goetz May 17 '23 at 16:28
  • I started to suspect as I wrote the question. wondering if this should be deleted. – Gonen I May 17 '23 at 16:29
  • 1
    Use `record User(String name) {}` – Holger Jun 14 '23 at 14:40

1 Answers1

1

Yes, user is immutable, but as you and @Brian Goetz noted, you can still mutate the property name.

banan3'14
  • 3,810
  • 3
  • 24
  • 47