How do I correctly reuse Jackson ObjectMapper?

前端 未结 4 523
耶瑟儿~
耶瑟儿~ 2021-02-01 12:10

I am happy with how the ObjectMapper works and general use within my application. What I would like to understand is the best way to implement the ObjectMapper to ensure it is r

4条回答
  •  南旧
    南旧 (楼主)
    2021-02-01 12:40

    As posted in other answers, the ObjectMapper is indeed Thread safe. But reusing the same object can decrease the performance of your application, since all - 1 threads can be locked at a given time waiting for the owner of the lock to complete the serialization/deserialization of JSON.

    This is especially critical on web servers such as Jetty or Tomcat: the overall performance of the entire server can be compromised, for instance, if you use the singleton ObjectMapper as entry/exit point of REST services - depending, of course, on your access load.

    So, my suggestion is to use a pool of ObjectMappers, to allow multiple Threads to use it, and in a way you don't have to recreate the mappers every time you need them. The number to ObjectMappers in the pool should be the same number of worker Threads of your application.

    More about: http://jackson-users.ning.com/forum/topics/pooling-objectmapper-for-performance

    -- EDIT --

    Ok, some users are really passionate about the Jackson lib to the point that they downvote this answer without even looking at the linked website. Anyway, this answer is based on my experience with the lib without any modifications (just using ObjectMapper, no extra classes, no custom serializer, no custom JSONFactory, nothing) at the time of the answer (2013). I don't use it anymore on my projects so I don't know about newer versions - but I guess it should be solved by now.

    As developer, if you're going to use Jackson or any other JSON reader/writer on your project, directly or indirectly, consider running a profiling tool on your server to see how the threads behave on high load. It's a simple step that doesn't harm.

提交回复
热议问题