Junior — Middle
How does the use of the lock() method differ from the async() method when managing asynchrony and locks in programming?
sobes.tech AI
Answer from AI
The lock() method is typically used for explicit lock acquisition (for example, in multithreaded programming) to ensure exclusive access to a resource. It blocks the current thread until the lock is acquired.
The async() method relates to asynchronous programming and starts a task or function asynchronously, without blocking the current thread. Instead of waiting for the operation to complete, async() allows the code to continue executing, and the result can be obtained later via await or a callback.
Main differences:
lock()blocks the thread until access to the resource is granted.async()does not block the thread but runs the operation in parallel.
Example in Java:
// Using lock
Lock lock = new ReentrantLock();
lock.lock();
try {
// critical section
} finally {
lock.unlock();
}
// Using async (with CompletableFuture)
CompletableFuture.supplyAsync(() -> {
// asynchronous task
return result;
});