英文:
ScopedValue appears is not immutable
问题
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?
英文:
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?
答案1
得分: 1
是的,user
是不可变的,但正如您和 @Brian Goetz 指出的,您仍然可以更改属性 name
。
英文:
Yes, user
is immutable, but as you and @Brian Goetz noted, you can still mutate the property name
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论