Skip to content

Commit c69c072

Browse files
committed
Volatile for concurrently access variables
1 parent 90fba18 commit c69c072

6 files changed

Lines changed: 45 additions & 18 deletions

File tree

‎java-does-usb/robustness.md‎

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -336,11 +336,24 @@ the device left open but `deviceOpenCount == 0` and no interface claimed. Since
336336
releases *claimed* interfaces, that device handle (still registered with the completion port) leaks
337337
until process exit.
338338

339-
---
340-
341-
## Open findings
339+
## 8. Visibility: shared flags are neither volatile nor consistently synchronized — **FIXED (all platforms)**
340+
341+
> **Status:** Fixed on 2026-07-06. All three listed items are now `volatile`:
342+
> `WindowsUsbDevice.showAsOpen`, `UsbDeviceImpl.connected`, and the two registry handler fields.
343+
> The same unlocked-`isOpened()` pattern exists on the other two platforms (the finding named
344+
> Windows only because that's where the review looked) and was fixed there too: `LinuxUsbDevice.fd`
345+
> and the `MacosUsbDevice.claimedInterfaces` reference are also `volatile` now (for the latter,
346+
> `isOpened()` only null-checks the reference; the list contents are only accessed while holding
347+
> the device monitor, so `volatile` on the reference suffices).
348+
>
349+
> In addition, `emitOnDeviceConnected` / `emitOnDeviceDisconnected` now read the handler field once
350+
> into a local before the null check. With `volatile` alone, a concurrent
351+
> `setOnDeviceConnected(null)` between the null check and the invocation would have thrown an NPE
352+
> that the catch block then mislabels as an exception *inside* the user's handler.
353+
>
354+
> Compile-verified; pure visibility changes of this kind are not exercisable by the test suite.
342355
343-
## 8. Visibility: shared flags are neither volatile nor consistently synchronized
356+
The original description follows.
344357

345358
- `showAsOpen`: written under the device monitor, but `isOpened()` (`WindowsUsbDevice.java:114`)
346359
reads it unlocked — `checkIsOpen`/`checkIsClosed` can act on stale state on a different thread.
@@ -353,6 +366,10 @@ until process exit.
353366
All are cheap to fix with `volatile`. Practical impact is low (stale reads, not corruption), but
354367
`isConnected()` returning `true` long after unplug is user-visible.
355368

369+
---
370+
371+
## Open findings
372+
356373
## 9. `messagePort` (remote) creation is unchecked (macOS)
357374

358375
`MacosAsyncTask.java:135`: `CFMessagePortCreateRemote` can return NULL (e.g. a
@@ -447,9 +464,8 @@ timeout rather than an infinite block).
447464

448465
## Recommended priority
449466

450-
Findings 1–7 are fixed (see above). Next up: the `volatile` flags of finding 8 and the
451-
macOS message-port null check of finding 9. Findings 10–12 are low-priority
452-
robustness notes.
467+
Findings 1–8 are fixed (see above). Next up: the macOS message-port null check of
468+
finding 9. Findings 10–12 are low-priority robustness notes.
453469

454470
The Linux fixes for findings 1–3 still need a hardware test run on a Linux machine, and the
455471
finding 7 fix a hardware regression run on Windows.

‎java-does-usb/src/main/java/net/codecrete/usb/common/UsbDeviceImpl.java‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,9 @@ public abstract class UsbDeviceImpl implements UsbDevice {
6363
protected int deviceProtocol;
6464
protected Version versionUsb;
6565
protected Version versionDevice;
66-
protected boolean connected;
66+
// volatile: written by the device monitor thread in disconnect(), read unlocked
67+
// via isConnected() and checkIsClosed()
68+
protected volatile boolean connected;
6769

6870
/**
6971
* Creates a new instance.

‎java-does-usb/src/main/java/net/codecrete/usb/common/UsbDeviceRegistry.java‎

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -32,14 +32,16 @@
3232
* and builds the initial device list.
3333
* </p>
3434
*/
35+
@SuppressWarnings("java:S3077")
3536
public abstract class UsbDeviceRegistry {
3637

3738
private static final System.Logger LOG = System.getLogger(UsbDeviceRegistry.class.getName());
3839

3940
private List<UsbDevice> devices;
4041
private Throwable failureCause;
41-
protected Consumer<UsbDevice> onDeviceConnectedHandler;
42-
protected Consumer<UsbDevice> onDeviceDisconnectedHandler;
42+
// volatile: set by the application thread, read by the device monitor thread
43+
protected volatile Consumer<UsbDevice> onDeviceConnectedHandler;
44+
protected volatile Consumer<UsbDevice> onDeviceDisconnectedHandler;
4345

4446
private final Lock lock = new ReentrantLock();
4547
private final Condition enumerationComplete = lock.newCondition();
@@ -86,23 +88,26 @@ public void setOnDeviceDisconnected(Consumer<UsbDevice> handler) {
8688
}
8789

8890
protected void emitOnDeviceConnected(UsbDevice device) {
89-
if (onDeviceConnectedHandler == null)
91+
// read once so a concurrent setOnDeviceConnected(null) cannot fail between check and call
92+
var handler = onDeviceConnectedHandler;
93+
if (handler == null)
9094
return;
9195

9296
try {
93-
onDeviceConnectedHandler.accept(device);
97+
handler.accept(device);
9498

9599
} catch (Exception e) {
96100
LOG.log(WARNING, "unhandled exception in 'onDeviceConnected' handler - ignoring", e);
97101
}
98102
}
99103

100104
protected void emitOnDeviceDisconnected(UsbDevice device) {
101-
if (onDeviceDisconnectedHandler == null)
105+
var handler = onDeviceDisconnectedHandler;
106+
if (handler == null)
102107
return;
103108

104109
try {
105-
onDeviceDisconnectedHandler.accept(device);
110+
handler.accept(device);
106111

107112
} catch (Exception e) {
108113
LOG.log(WARNING, "unhandled exception in 'onDeviceDisconnected' handler - ignoring", e);

‎java-does-usb/src/main/java/net/codecrete/usb/linux/LinuxUsbDevice.java‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,8 @@ public class LinuxUsbDevice extends UsbDeviceImpl {
4343

4444
private static final MemorySegment DRIVER_NAME_USBFS = Arena.global().allocateFrom("usbfs");
4545

46-
private int fd = -1;
46+
// volatile: written under the device monitor, read unlocked via isOpened()
47+
private volatile int fd = -1;
4748

4849
private final LinuxAsyncTask asyncTask;
4950

‎java-does-usb/src/main/java/net/codecrete/usb/macos/MacosUsbDevice.java‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@
5151
* asynchronous transfer and waiting for the completion.
5252
* </p>
5353
*/
54-
@SuppressWarnings({"SynchronizationOnLocalVariableOrMethodParameter", "java:S2160"})
54+
@SuppressWarnings({"SynchronizationOnLocalVariableOrMethodParameter", "java:S2160", "java:S3077"})
5555
public class MacosUsbDevice extends UsbDeviceImpl {
5656

5757
private final MacosAsyncTask asyncTask;
@@ -60,7 +60,9 @@ public class MacosUsbDevice extends UsbDeviceImpl {
6060
// Currently selected configuration
6161
private int configurationValue;
6262
// Details about interfaces that have been claimed
63-
private List<InterfaceInfo> claimedInterfaces;
63+
// (volatile: written under the device monitor, read unlocked via isOpened();
64+
// the list contents are only accessed while holding the device monitor)
65+
private volatile List<InterfaceInfo> claimedInterfaces;
6466
// Details about endpoints of current alternate settings (for claimed interfaces)
6567
private Map<Byte, EndpointInfo> endpoints;
6668

‎java-does-usb/src/main/java/net/codecrete/usb/windows/WindowsUsbDevice.java‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,8 +85,9 @@ public class WindowsUsbDevice extends UsbDeviceImpl {
8585
/**
8686
* Indicates if {@link #open()} has been called. Since separate interfaces can have separate underlying
8787
* Windows device, {@link #claimInterface(int)} instead of {@link #open()} will open the Windows device.
88+
* (volatile: written under the device monitor, read unlocked via {@link #isOpened()})
8889
*/
89-
private boolean showAsOpen;
90+
private volatile boolean showAsOpen;
9091

9192
WindowsUsbDevice(String devicePath, int vendorId, int productId, MemorySegment configDesc, boolean isComposite) {
9293
super(devicePath, vendorId, productId);

0 commit comments

Comments
 (0)