RDS
RDS

Reputation: 21

using class level variable in class which handle multiple request

I have a class as written as follows, method doSomethingForMe() of which gets called from a servlet. The servlet can issue multiple request for the same method. The Servlet gets the object from Spring. As this class is getting initialized by Spring Bean factory.

public class ClassLevelVariableTest
{
  private List<String> errorLists;

   public void doSomethingForMe()
   {
     errorLists = new ArrayList<>();
     // plus do the rest functionality
     if (!errorLists.isEmpty())
      {
        prepareErrorList(errorLists);
      }
   }

  private void prepareErrorList(List<String> errorLists)
  {
    for (String errorString : errorLists)
    {
      System.out.println(errorString);
    }
  }
}

So my first query is: Is there a chance of getting the same object of errorLists variable in subsequent requests?

Is there a chance of getting the variable overridden by second request?

Upvotes: 1

Views: 1132

Answers (1)

tddmonkey
tddmonkey

Reputation: 21184

If your bean is instantiated for every request then no, you are fine. If Spring injects a single one reused for every request then you have a problem. You can fix this easily by not storing errorLists as an instance variable. Change your code to this:

public class ClassLevelVariableTest
{

    public void doSomethingForMe()
    {
         List<String> errorLists = new ArrayList<>();

It doesn't seem like you're using errorLists as an instance variable so you should be fine.

Upvotes: 2

Related Questions