Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
walkingbear opened this issue May 17, 2024 · 0 comments

Comments

@walkingbear
Copy link

walkingbear commented May 17, 2024

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();
                }
        }
}
        
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant