Junior — Middle
What methods are used to prevent conflicts when working with primitive data types in a multithreaded environment?
sobes.tech AI
Answer from AI
To prevent conflicts when working with primitive data types in a multithreaded environment in Java, the following methods are used:
-
Synchronization (synchronized) — locking code or methods so that only one thread can execute the critical section at a time.
-
Classes from the java.util.concurrent.atomic package — for example, AtomicInteger, AtomicBoolean, which provide atomic operations without explicit synchronization.
-
Volatile — a keyword that guarantees visibility of variable changes between threads but does not ensure atomicity of complex operations.
Example of using AtomicInteger:
import java.util.concurrent.atomic.AtomicInteger;
public class Counter {
private AtomicInteger count = new AtomicInteger(0);
public void increment() {
count.incrementAndGet();
}
public int getCount() {
return count.get();
}
}
This approach allows safe modification of primitive values in a multithreaded environment without locks.