Important Notice: Our web hosting provider recently started charging us for additional visits, which was unexpected. In response, we're seeking donations. Depending on the situation, we may explore different monetization options for our Community and Expert Contributors. It's crucial to provide more returns for their expertise and offer more Expert Validated Answers or AI Validated Answers. Learn more about our hosting issue here.

Why are local variables always thread safe?

local safe thread variables
0
Posted

Why are local variables always thread safe?

0

Local variables are stored on the Thread calling stack. They are NOT shared between different calling threads. This is true in almost any programming languages, unless you declare the local variable as static such as in c/c++/VB, and then it is shared. However, Java does not allow that to happen. It does not matter it is static method or instance method. However, be cautious when your method modifies something else which is not local. That is when synchronized keyword needs to be kicked in. There is one thing in Java easily causes confusion. Java objects created local are not stored on thread calling stacks. They are always on the heap, only the local references are stored on the calling stack. If you make those objects available outside the local range, it will become thread unsafe. For example, if you store it in to the HttpSession, it is not thread safe any more.This is very different than c++ local objects, such as Object o; which is truely local. The Java object created local is e

Related Questions

What is your question?

*Sadly, we had to bring back ads too. Hopefully more targeted.

Experts123