-
Notifications
You must be signed in to change notification settings - Fork 215
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add a helper class for working with attached computers
One of the easiest things to mess up with writing a custom peripheral is handling attached peripherals. IPeripheral.{attach,detach} are called from multiple threads, so naive implementations that just store computers in a set/list will at some point throw a CME. Historically I've suggested using a concurrent collection (i.e. ConcurrentHashMap). While this solves the problems of CMEs, it still has some flaws. If a computer is detached while iterating over the collection, the iterator will still yield the now-detached peripheral, causing usages of that computer (e.g. queueEvent) to throw an exception. The only fix here is to use a lock when updating and iterating over the collection. This does come with some risks, but I think they are not too serious: - Lock contention: Contention is relatively rare in general (as peripheral attach/detach is not especially frequent). If we do see contention, both iteration and update actions are cheap, so I would not expect the other thread to be blocked for a significant time. - Deadlocks: One could imagine an implementation if IComputerAccess that holds a lock both when detaching a peripheral and inside queueEvent. If we queue an event on one thread, and try to detach on the other, we could see a deadlock: Thread 1 | Thread 2 ---------------------------------------------------------- AttachedComputerSet.queueEvent | MyModem.detach (take lock #1) | (take lock #2) -> MyModem.queueEvent | AttachedComputerSet.remove (wait on lock #2) | (wait on lock #1) Such code would have been broken already (some peripherals already use locks), so I'm fairly sure we've fixed this in CC. But definitely something to watch out for. Anyway, the long and short of it: - Add a new AttachedComputerSet that can be used to track the computers attached to a peripheral. We also mention this in the attach/detach docs, to hopefully make it a little more obvoius. - Update speakers and monitors to use this new class.
- Loading branch information
Showing
4 changed files
with
147 additions
and
23 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
129 changes: 129 additions & 0 deletions
129
projects/core-api/src/main/java/dan200/computercraft/api/peripheral/AttachedComputerSet.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,129 @@ | ||
// SPDX-FileCopyrightText: 2024 The CC: Tweaked Developers | ||
// | ||
// SPDX-License-Identifier: MPL-2.0 | ||
|
||
package dan200.computercraft.api.peripheral; | ||
|
||
import javax.annotation.Nullable; | ||
import java.util.HashSet; | ||
import java.util.Set; | ||
import java.util.concurrent.ConcurrentHashMap; | ||
import java.util.concurrent.CopyOnWriteArraySet; | ||
import java.util.concurrent.locks.ReentrantReadWriteLock; | ||
import java.util.function.Consumer; | ||
|
||
/** | ||
* A thread-safe collection of computers. | ||
* <p> | ||
* This collection is intended to be used by peripherals that need to maintain a set of all attached computers. | ||
* <p> | ||
* It is recommended to use over Java's built-in concurrent collections (e.g. {@link CopyOnWriteArraySet} or | ||
* {@link ConcurrentHashMap}), as {@link AttachedComputerSet} ensures that computers cannot be accessed after they are | ||
* detached, guaranteeing that {@link NotAttachedException}s will not be thrown. | ||
* <p> | ||
* To ensure this, {@link AttachedComputerSet} is not directly iterable, as we cannot ensure that computers are not | ||
* detached while the iterator is running (and so trying to use the computer would error). Instead, computers should be | ||
* looped over using {@link #forEach(Consumer)}. | ||
* | ||
* <h2>Example</h2> | ||
* | ||
* <pre>{@code | ||
* public class MyPeripheral implements IPeripheral { | ||
* private final AttachedComputerSet computers = new ComputerCollection(); | ||
* | ||
* @Override | ||
* public void attach(IComputerAccess computer) { | ||
* computers.add(computer); | ||
* } | ||
* | ||
* @Override | ||
* public void detach(IComputerAccess computer) { | ||
* computers.remove(computer); | ||
* } | ||
* } | ||
* }</pre> | ||
* | ||
* @see IComputerAccess | ||
* @see IPeripheral#attach(IComputerAccess) | ||
* @see IPeripheral#detach(IComputerAccess) | ||
*/ | ||
public final class AttachedComputerSet { | ||
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); | ||
private final Set<IComputerAccess> computers = new HashSet<>(0); | ||
|
||
/** | ||
* Add a computer to this collection of computers. This should be called from | ||
* {@link IPeripheral#attach(IComputerAccess)}. | ||
* | ||
* @param computer The computer to add. | ||
*/ | ||
public void add(IComputerAccess computer) { | ||
lock.writeLock().lock(); | ||
try { | ||
computers.add(computer); | ||
} finally { | ||
lock.writeLock().unlock(); | ||
} | ||
} | ||
|
||
/** | ||
* Remove a computer from this collection of computers. This should be called from | ||
* {@link IPeripheral#detach(IComputerAccess)}. | ||
* | ||
* @param computer The computer to remove. | ||
*/ | ||
public void remove(IComputerAccess computer) { | ||
lock.writeLock().lock(); | ||
try { | ||
computers.remove(computer); | ||
} finally { | ||
lock.writeLock().unlock(); | ||
} | ||
} | ||
|
||
/** | ||
* Apply an action to each computer in this collection. | ||
* | ||
* @param action The action to apply. | ||
*/ | ||
public void forEach(Consumer<? super IComputerAccess> action) { | ||
lock.readLock().lock(); | ||
try { | ||
computers.forEach(action); | ||
} finally { | ||
lock.readLock().unlock(); | ||
} | ||
} | ||
|
||
/** | ||
* {@linkplain IComputerAccess#queueEvent(String, Object...) Queue an event} on all computers. | ||
* | ||
* @param event The name of the event to queue. | ||
* @param arguments The arguments for this event. | ||
* @see IComputerAccess#queueEvent(String, Object...) | ||
*/ | ||
public void queueEvent(String event, @Nullable Object... arguments) { | ||
forEach(c -> c.queueEvent(event, arguments)); | ||
} | ||
|
||
/** | ||
* Determine if this collection contains any computers. | ||
* <p> | ||
* This method is primarily intended for presentation purposes (such as rendering an icon in the UI if a computer | ||
* is attached to your peripheral). Due to the multi-threaded nature of peripherals, it is not recommended to guard | ||
* any logic behind this check. | ||
* <p> | ||
* For instance, {@code if(computers.hasComputers()) computers.queueEvent("foo");} contains a race condition, as | ||
* there's no guarantee that any computers are still attached within the body of the if statement. | ||
* | ||
* @return Whether this collection is non-empty. | ||
*/ | ||
public boolean hasComputers() { | ||
lock.readLock().lock(); | ||
try { | ||
return !computers.isEmpty(); | ||
} finally { | ||
lock.readLock().unlock(); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters