Sobes.tech
Junior — Middle

Kas teil on kogemusi @Async annotatsiooni kasutamisel ülesannete asünkroonseks töötlemiseks?

sobes.tech AI

Vastus AI-lt

The @Async annotation in Spring allows methods to be executed asynchronously, that is, in a separate thread, without blocking the main execution thread. To use it, you need to enable asynchronous support via @EnableAsync in the configuration.

Example:

@Service
public class MyService {

    @Async
    public CompletableFuture<String> asyncMethod() {
        // Long operation
        return CompletableFuture.completedFuture("Result");
    }
}

When calling asyncMethod(), execution will continue immediately, and the method will run in another thread. This is useful for tasks that do not require an immediate result, such as sending emails or processing data in the background.