Junior — Middle
What methods of background task execution do you know using asynchronous programming?
sobes.tech AI
Answer from AI
In Java, to manage concurrent access to an object, the following main methods are used:
- Synchronization using the
synchronizedkeyword — synchronize methods or code blocks so that only one thread can execute them at a time.
public class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
- Using classes from
java.util.concurrentpackage — such asReentrantLock,ReadWriteLock,Semaphore, which provide more flexible locking control.
import java.util.concurrent.locks.ReentrantLock;
public class Counter {
private int count = 0;
private final ReentrantLock lock = new ReentrantLock();
public void increment() {
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}
public int getCount() {
lock.lock();
try {
return count;
} finally {
lock.unlock();
}
}
}
- Using atomic classes from
java.util.concurrent.atomic— such asAtomicInteger, which provide atomic operations without explicit locking.
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();
}
}
These methods help avoid race conditions and ensure correct operation in multithreaded environments.