Home     RSSRSS

Concurrency, Thread Safety and Local Variables

August 12, 2016 by kiranbadi1991 | Filed under Development, Performance Center, Performance Engineering, Performance Test Tools.

One of the most of the common reason for concurrency issues I often see in web application is due to concurrent access of data stored in variables. Generally in servlets , data in variables are often stored as Local variables, Instance Variables, Class Variables , request attributes, session attributes and context attributes.

Below example simplest I can think of for storing data as local variable and accessing it in a thread safe manner

public class MyServlet extends httpServlet {

  // mylocalage is localvariable here for this servlet.

    public void printAge(){
              int mylocalage = 0;
      mylocalageage = mylocalage - 10;
      System.out.println("My age 10 years earlier was: " + mylocalage);
      

    }
}

Its considered that by design that data stored in local variable is thread safe.

Every thread accessing the above servlet will have their own values and they will not interface with each other.

image

Local variables are stored in stack in Java. So data stored in these variables are thread safe.

← Previous

Tags: , ,

Comments are disabled