Sobes.tech
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:

  1. Synchronization using the synchronized keyword — 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;
    }
}
  1. Using classes from java.util.concurrent package — such as ReentrantLock, 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();
        }
    }
}
  1. Using atomic classes from java.util.concurrent.atomic — such as AtomicInteger, 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.

What methods of background task execution do you know… - sobes.tech