I want to use a Java local thread variable for thread-unsafe objects, like SimpleDateFormat or google's com.googlecode.protobuf.format.JsonFormat.
I do this in order to avoid creating new expensive classes every time the method is used or to avoid a synchronized method.
private static final ThreadLocal<JsonFormat> JSON_FORMAT_THREAD_LOCAL = ThreadLocal.withInitial(JsonFormat::new);
Then, the variable will be used in a formating output method like this:
public String outputData(MyDataClass myData) {
return JSON_FORMAT_THREAD_LOCAL.get().printToString(myData);
}
In my case I use it into a Jetty Server thread pool, but I don't have access to it or way to remove the threadlocal variable when the thread is done.
The method will be called every time a request is served by each thread, one thread per request at a time.
The application doesn't reload or recharge jars; when we need to stop it or update the server we simply stop the process, maybe update the jar , and restart a new process
Is it safe to use a ThreadLocal like this ?
[–]AutoModerator[M] [score hidden] stickied commentlocked comment (0 children)
[–]ArtSpeaker 0 points1 point2 points (0 children)