Search code examples
spring-boothealth-check

Is HealthIndicator thread safe?


Do I have to make the method check() thread-safe?

@Component
public class MyHealthIndicator implements HealthIndicator {

    @Autowired
    private MyComponent myComponent;

    @Override
    public Health health() {
        int errorCode = myComponent.check();
        if (errorCode != 0) {
            return Health.down().withDetail("Error Code", errorCode).build();
        }
        return Health.up().build();
    }

}

Is the request to the corresponding actuator endpoint executed in a separated thread? The app logic itself has only one thread.


Solution

  • To answer the direct question you asked ...

    Do I have to make the method check() thread-safe?

    You don't have to make it thread-safe, but if your application requires that myComponent.check() is only executed by a single thread at once, then yes, you'll need to mark it synchronized.

    To answer the more general question

    Is HealthIndicator thread safe?

    By default, each health check initiated (often by an HTTP call, perhaps to /actuator/health) will run on a single thread, and check the health of each component that's registered a HealthIndicator sequentially, and thus the individual request is single-threaded.

    HOWEVER ... there's nothing to stop multiple clients each making a request to /actuator/health at the same time, and thus there may be multiple health checks in progress at the same time, each of which will be executing on a different thread.

    Therefore, if there's some reason why myComponent.check() should not be executed by more than one thread concurrently, you will need to mark it synchronized or else add in some other concurrency limiting mechanisms (e.g. java.util.concurrent.Semaphore).