Zum Inhalt springen

Non Thread Safe Shared State (ARCH4038)

Dieser Inhalt ist noch nicht in deiner Sprache verfügbar.

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.