1

My class looks something like this:

public Class A {

     private static final ObjectMapper mapper = new ObjectMapper();

     public String get(String key) {
          JsonNode nod = mapper.readTree(getFromCache(key));
     }
}

Multiple threads would be accessing this method. Do I need to synchronize it? Do I need to move the mapper inside the method?

Aditya W
  • 652
  • 8
  • 20
Farhad
  • 388
  • 2
  • 13
  • 2
    If that's the Objectmapper from Jackson Library, the answer seems to be that it is safe (http://stackoverflow.com/q/3907929/5077154). However, the general answer to your question is "it depends". – Insac Oct 04 '16 at 06:13

3 Answers3

5

This depends on the implementation of ObjectMapper. For a possible answer, see: Should I declare Jackson's ObjectMapper as a static field?

It is not possible to tell from the code sample you have provided because we don't know what that ObjectMapper is.

To find the answer you would need to check the javadoc of ObjectMapper. Or failing that, the implementation.

If you are unsure, you could:

  • create a new ObjectMapper inside the method so there is a new object each time,
  • create a ThreadLocal, so each thread has it's own object

Creating objects is very cheap on the JVM (unless they do expensive operations like scanning the class path, etc).

Community
  • 1
  • 1
WW.
  • 23,793
  • 13
  • 94
  • 121
  • 3
    And if you use `ThreadLocal`, beware of "leaks" from long-lived threads like thread pool workers. The thread local object will hang around as long as the thread is alive, even if the thread ends up being assigned to some completely different task. – Kevin Krumwiede Oct 04 '16 at 06:14
  • Yes, the ObjectMapper is the import org.codehaus.jackson.map.ObjectMapper; – Farhad Oct 04 '16 at 06:49
0

There is one copy of static variable per class-loader that loaded this class. This more-or-less means per-process, however you need to be aware of the difference.

E.g. when two web-apps have the same class bundled, the class will be loaded twice, thus having two copies of the same static field.

If you need a variable having independent value on a thread basis, have a look at ThreadLocal

Vinod Bokare
  • 86
  • 3
  • 8
0

As WW. mentioned it is dependent upon the ObjectMapper.readTree implementation. There are multiple factors which decides whether the method is thread safe or not.

Like :

  1. Whether the method is synchronized or not
  2. Does method uses variables which are declared outside the method
Sachin Gorade
  • 1,427
  • 12
  • 32