0
votes

I'm trying to learn whether in Java 8, a nested static class in a controller (singleton class) is also static and could be shared between requests?

This is legacy code I'm cleaning up because of a possible race condition: The controller had multiple private fields. I moved them to a static nested class and created an instance of that class each time the request hits the controller. Then I pass that object around to private methods for calculations.

I'm being told that static nested classes in singletons have only one instance of the sub-class in memory, and if it's hit with 2 requests, the second one will stick. Also being warned that someone could move this static class outside, which is not a good approach to take (?)

There are a lot of answers around the difference between static class & singletons. Have found on Oracle docs: In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.

=== But I haven't found anything about a static nested class IN a singleton ===

I tried it out: paused a thread in handleRequest and started a second one, and found the instances of the static nested class were different and contained different values. This is what I expect, given the documentation, but I don't know for sure, because I can't find anything about a static nested class WITHIN A SINGLETON.

Am I missing something? Is it possible this will fail? Is there a better solution?

public class MyController extends WebContentGenerator implements Controller {

  @Override
  public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception
  {
    ReportParameters params = new ReportParameters();
    initVars(request, params);
    doWork(params);
    return null;
  }

  private void initVars(HttpServletRequest request, ReportParameters params)
  {
    params.flag = "Y".equals(request.getParameter("flag"));
    params.message = "Hello world";
  }

  private void doWork(ReportParameters params)
  {
    if (params.flag)
      params.message = "foo";
  }

  private static class ReportParameters
  {
    private boolean flag;
    private String message;
  }
}
1

1 Answers

5
votes

A static nested class is no different than a top-level class: every time you use new to create an instance, you... create an instance. If you create an instance more than once, then by definition, it's not a singleton. The fact that it's created from a singleton is competely irrelevant. The JVM doesn't even have the notion of a singleton: it's just an architectural choice.