gpt4 book ai didi

Java - 在同步 setter 函数期间调用同步 getter 函数是否是操作共享变量的正确方法?

转载 作者:行者123 更新时间:2023-11-29 07:44:31 24 4
gpt4 key购买 nike

我有几个线程试图为非线程安全的自定义数据结构(您可以将其想象为类似于 HashMap)中的某个键增加计数器。我想知道在这种情况下增加计数器的正确方法是什么。

同步自增函数是否足够,还是我还需要同步get操作?

public class Example {

private MyDataStructure<Key, Integer> datastructure = new CustomDataStructure<Key, Integer>();

private class MyThread implements Runnable() {

private synchronized void incrementCnt(Key key) {
// from the datastructure documentation: if a value already exists for the given key, the
// previous value will be replaced by this value
datastructure.put(key, getCnt(key)+1);

// or can I do it without using the getCnt() function? like this:
datastructure.put(key, datastructure.get(key)+1));
}

private synchronized int getCnt(Key key) {
return datastructure.get(key);
}

// run method...
}
}

例如,如果我有两个线程 t1、t2,我会这样:

t1.incrementCnt();
t2.incrmentCnt();

这会导致任何形式的僵局吗?有没有更好的方法来解决这个问题?

最佳答案

此代码的主要问题是它可能无法提供对datastructure 的同步访问,因为访问代码是在内部类的this 上同步的。这对于 MyThread 的不同实例是不同的,因此不会发生互斥。

更正确的方法是让datastructure成为final字段,然后在上面同步:

private final MyDataStructure<Key, Integer> datastructure = new CustomDataStructure<Key, Integer>();

private class MyThread implements Runnable() {

private void incrementCnt(Key key) {
synchronized (datastructure) {
// or can I do it without using the getCnt() function? like this:
datastructure.put(key, datastructure.get(key)+1));
}
}

只要所有数据访问都是使用同步(数据结构)完成的,代码就是线程安全的并且只使用datastructure.get(...) 是安全的.不应该有死锁,因为死锁只有在有多个锁竞争时才会发生。

关于Java - 在同步 setter 函数期间调用同步 getter 函数是否是操作共享变量的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27094247/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com