Senior
Code task: synchronized get/set and multithreading (screenshot with code)
sobes.tech AI
Answer from AI
In Java, the synchronized keyword is often used to ensure thread-safe access to data. It allows synchronizing methods or blocks of code so that only one thread can execute them at a time.
Example of synchronized get/set for a field in multithreading:
public class Counter {
private int count = 0;
public synchronized int getCount() {
return count;
}
public synchronized void setCount(int count) {
this.count = count;
}
public synchronized void increment() {
count++;
}
}
Here, the methods getCount, setCount, and increment are synchronized, which guarantees atomicity of operations and prevents race conditions.
If more fine-grained control is needed, you can use synchronized blocks:
public class Counter {
private int count = 0;
private final Object lock = new Object();
public int getCount() {
synchronized(lock) {
return count;
}
}
public void setCount(int count) {
synchronized(lock) {
this.count = count;
}
}
}
This allows synchronizing only the necessary parts of the code, improving performance.
For more complex scenarios, consider using classes from the java.util.concurrent package, such as AtomicInteger or ReentrantLock.