Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

【复合操作的非原子性】以下ConcurrentHashMap操作也不会实现预期的anotherValue #2668

Open
Labels
questionFurther information is requested
@GuZyx

Description

// 线程 A
map.putIfAbsent(key, value);

// 线程 B
map.putIfAbsent(key, anotherValue);

eg:

 public static void main(String[] args) {
 Map<String, Integer> map = new ConcurrentHashMap<>();
 // 初始时 map 为空
 // 计算键 "key1" 对应的值,如果不存在则根据计算逻辑生成值
 Integer value1 = map.putIfAbsent("key1", 1);
 System.out.println("map = " + map); // 输出: map = {key1=1}
 System.out.println("value1 = " + value1); // 输出: value1 = 1
 // 再次计算键 "key1" 对应的值,由于键已存在,直接返回已有的值
 Integer value2 = map.putIfAbsent("key1", 2);
 System.out.println("map = " + map); // 输出: map = {key1=1}
 System.out.println("value2 = " + value2); // 输出: value2 = 1
 }

以上操作也并不会实现预期的 (key, anotherValue)。

Image

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Projects

    No projects

    Milestone

    No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

        AltStyle によって変換されたページ (->オリジナル) /