swagger-api / swagger-core

Examples and server integrations for generating the Swagger API Specification, which enables easy access to your REST API
http://swagger.io
Apache License 2.0
7.36k stars 2.17k forks source link

io.swagger.v3.core.util.Json public static method mapper() is not thread safe #4672

Open walkingbear opened 1 month ago

walkingbear commented 1 month ago

Hi, When I'm using Swagger for API document generation and found below issue. This issue exists across multiple tags and event in the master and Json31 class.

The public static method mapper() like below is not thread safe. It appears that the "mapper" field is designed to be lazily initialized and want to initialize only once. But current implementation does not give this guarantee. If we want the lazy and only once initialization semantic, we need to use double checked locking or simply synchronize the mapper() method or use private static class, otherwise, the mapper has chance to be initialized multiple times by different threads in multi threads scenario.

current implementation:

    private static ObjectMapper mapper;

    public static ObjectMapper mapper() {
        if (mapper == null) {
            mapper = ObjectMapperFactory.createJson();
        }
        return mapper;
    }

suggested implementation using double checked locking


private static volatile ObjectMapper mapper;
public static ObjectMapper mapper() {
        if (mapper == null) {
            synchronized(Json.class) {
                if (mapper == null) {
                    mapper = ObjectMapperFactory.createJson();
                }
        }
}