ScopedValue 不是不可变的

huangapple go评论61阅读模式
英文:

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&lt;User&gt; LOGGED_IN_USER = ScopedValue.newInstance();
	
 public static void main(String[] args) {
   User loggedInUser = new User(); loggedInUser.name = &quot;ABC&quot;;
   ScopedValue.where(LOGGED_IN_USER, loggedInUser, () -&gt; f1()); // value will be available through f1
 }

private static void f1() {
	User user = LOGGED_IN_USER.get();
	System.out.println(&quot;In f1 user = &quot; + user.name);
	user.name = &quot;DEF&quot;;
	f2();
}

private static void f2() {
	User user = LOGGED_IN_USER.get();
	System.out.println(&quot;In f2 user = &quot; + 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.

huangapple
  • 本文由 发表于 2023年5月17日 23:55:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76274010.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定