Aller au contenu

Non Thread Safe Shared State (ARCH4038)

Ce contenu n’est pas encore disponible dans votre langue.

Key java.async.non-volatile-shared-field · Severity warning · Category async

Mutable shared fields that are not volatile/atomic and are read or written outside a synchronized block cause visibility issues and race conditions under concurrent access.

class Counter {
private boolean running; // shared, unprotected
void start() { running = true; }
void stop() { running = false; } // from another thread
}
class Counter {
private volatile boolean running; // visibility guaranteed
void start() { running = true; }
void stop() { running = false; }
}

Make the shared field volatile, use an AtomicX type, or guard every access with synchronized/a lock.