gpt4 book ai didi

java避免死锁

转载 作者:行者123 更新时间:2023-11-29 06:53:35 26 4
gpt4 key购买 nike

我们的应用程序(使用 java)非常复杂,我有下面的示例棘手代码,将在多线程环境中使用。

现在的问题是当我运行下面的代码时(将其作为独立的主程序运行),我遇到了死锁。

位置类:-

public class Location implements Runnable {

private final int id;

private final int[] dependentLocationIds;

private final Lock lock = new ReentrantLock();

public Location(int id, int[] dependentLocationIds) {
this.id = id;
this.dependentLocationIds = dependentLocationIds;
}

public int getId() {
return id;
}

public boolean blockLocation() {
lock.lock();
return true;
}

public boolean releaseLocation() {
lock.unlock();
return true;
}

public boolean occupy() {
boolean occupationStatus = false;
//order ids first
Arrays.sort(dependentLocationIds);

lock.lock();
try {

//below sleep temporarily added to track the progress slowly
Thread.sleep(1000);

//Check dependentLocations are NOT being modified concurrently
for(int id : dependentLocationIds) {
Location location = LocationHelper.getLocation(id);
System.out.println(Thread.currentThread().getName()+": blocking required dependent location :"+id);
location.blockLocation();
}
//the above blocked Locations will be released in leave()

//complex business logic to check and then make occupationStatus to true
occupationStatus = true;
System.out.println(id + ": location occupied by:"+Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if(!occupationStatus) {
lock.unlock();
}
//if occupationStatus is true, the lock will be released in leave()
}
return occupationStatus;
}

public boolean leave() {
boolean leaveStatus = false;
//order ids first
Arrays.sort(dependentLocationIds);
try {
//below sleep temporarily added to track the progress slowly
Thread.sleep(1000);

//complex business logic to check and then make leaveStatus to true
leaveStatus = true;

//now release dependent locations in reverse order
for(int i=dependentLocationIds.length; i>0;i--) {
Location location = LocationHelper.getLocation(id);
System.out.println(Thread.currentThread().getName()+": releasing required dependent location :"+id);
location.releaseLocation();
}

System.out.println(id + ": location released by "+Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
return leaveStatus;
}

public void run() {
occupy();
//some business logic goes here
leave();
}

public static void main(String[] args) {
List<Location> locations = LocationHelper.getLocations();

for(Location location : locations) {
//Each location runs in different threads here
new Thread(location, "THREAD-"+location.getId()).start();
}
}
}

LocationHelper 类:-

public class LocationHelper {

private static final List<Location> locations = new ArrayList<>();

static {
int[] locationids1 = {2, 3, 4, 5};
Location location1 = new Location(1, locationids1);
locations.add(location1);

int[] locationids2 = {1, 3, 4};
Location location2 = new Location(2, locationids2);
locations.add(location2);

int[] locationids3 = {1, 2, 4};
Location location3 = new Location(3, locationids3);
locations.add(location3);

int[] locationids4 = {3, 5};
Location location4 = new Location(4, locationids4);
locations.add(location4);

int[] locationids5 = {1, 2, 3, 4};
Location location5 = new Location(5, locationids5);
locations.add(location5);
}

public static List<Location> getLocations() {
return locations;
}

public static Location getLocation(int id) {
Location required = null;

for(Location location : locations) {
if(location.getId() == id) {
required = location;
}
}
return required;
}
}

The core requirement is when I am updating a particular 'Location' object, NONE of the dependent 'Location' objects should be allowed to change. So I am trying to lock the dependent objects as well, which is where the complexity arises.

我曾尝试根据“位置 id”(唯一)对位置对象进行排序,然后锁定位置对象以避免死锁,但没有成功。

请问如何修改这段代码以避免死锁?

如何重构“位置”类以消除上述复杂性?或者,'Location' 类是否还有其他更好的设计选项(使用并发 api)来简化上述逻辑?请帮忙。

最佳答案

the problem is when I run the below code (taken to run it as stand alone main), I am encountering dead locks.

我一点也不惊讶。事实上,我无法想象您期望您的代码如何工作。您启动了一堆线程,每个线程都尝试锁定系统中五个 Location 实例中的几个。死锁所需要做的就是让两个线程各自锁定一个位置,而另一个线程想要锁定。

例如,第一个线程从锁定位置 1 开始,它尝试锁定的位置是位置 2。第二个线程从锁定位置 2 开始,它尝试锁定的位置是位置 1。如果每个线程在尝试获取第二个锁之前都成功获取了第一个锁,然后你就完蛋了,而且你的程序中有很多这样的死锁机会,所以程序发生死锁的可能性很小。

最简单的解决方案是避免尝试并行执行所有这些锁定。当然,那么根本不需要锁定。或者,对于此特定代码(但可能不是您的较大代码),您可以使用 ReentrantReadWriteLock 的读取端,它允许多个线程同时获取它。另一方面,如果没有人获得关联的写锁,这又等同于根本没有锁定。

订购锁获取也应该可以解决您的问题,但这样做似乎与问题不相容。具体来说,我观察到每个 Location 首先锁定 自身,但随后可能还需要锁定其他位置的任意组合,包括那些排序较早的位置。假设第一次锁定是必不可少的(即你不能将其作为后续锁定序列的一部分执行)并且你不能限制 Locations 仅锁定具有更大 ID 的其他位置,我真的不除了序列化 Location 的运行之外,还有一种方法可以安全地执行此操作。

关于java避免死锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39961907/

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