Skip to content

Commit 42d5774

Browse files
SquidDevSirEndii
authored andcommitted
Fix thread-safety issues with BasePeripheral's computer list
There's a race condition here as attach/detach/getConnectedComputers may be called from multiple threads. While we could switch to a CoW list, it's probably nicer to use a ConcurrentHashMap like CC does.
1 parent cc938f3 commit 42d5774

File tree

3 files changed

+5
-6
lines changed

3 files changed

+5
-6
lines changed

src/main/java/de/srendi/advancedperipherals/common/blocks/base/PeripheralBlockEntity.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ public void invalidateCaps() {
108108
@NotNull
109109
protected abstract T createPeripheral();
110110

111-
public List<IComputerAccess> getConnectedComputers() {
111+
public Iterable<IComputerAccess> getConnectedComputers() {
112112
if (peripheral == null) // just avoid some NPE in strange cases
113113
return Collections.emptyList();
114114
return peripheral.getConnectedComputers();

src/main/java/de/srendi/advancedperipherals/lib/peripherals/BasePeripheral.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,13 @@
1515
import org.jetbrains.annotations.Nullable;
1616

1717
import java.util.*;
18+
import java.util.concurrent.ConcurrentHashMap;
1819
import java.util.function.BiConsumer;
1920
import java.util.function.Consumer;
2021

2122
public abstract class BasePeripheral<O extends IPeripheralOwner> implements IBasePeripheral<O>, IDynamicPeripheral {
2223

23-
protected final List<IComputerAccess> connectedComputers = new ArrayList<>();
24+
protected final Set<IComputerAccess> connectedComputers = Collections.newSetFromMap(new ConcurrentHashMap<>());
2425
protected final String type;
2526
protected final O owner;
2627
protected final List<BoundMethod> pluggedMethods = new ArrayList<>();
@@ -63,7 +64,7 @@ protected void addPlugin(@NotNull IPeripheralPlugin plugin) {
6364
}
6465

6566
@Override
66-
public List<IComputerAccess> getConnectedComputers() {
67+
public Iterable<IComputerAccess> getConnectedComputers() {
6768
return connectedComputers;
6869
}
6970

src/main/java/de/srendi/advancedperipherals/lib/peripherals/IBasePeripheral.java

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,10 @@
44
import dan200.computercraft.api.peripheral.IPeripheral;
55
import de.srendi.advancedperipherals.common.addons.computercraft.owner.IPeripheralOwner;
66

7-
import java.util.List;
8-
97
public interface IBasePeripheral<T extends IPeripheralOwner> extends IPeripheral {
108
boolean isEnabled();
119

12-
List<IComputerAccess> getConnectedComputers();
10+
Iterable<IComputerAccess> getConnectedComputers();
1311

1412
T getPeripheralOwner();
1513
}

0 commit comments

Comments
 (0)