Farhad Farhad - 1 year ago 71
Java Question

Is it safe to use a static object in a non-static method when multiple threads are accessing it?

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?

Answer Source

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).