You are on page 1of 1

Thread safety and Shared resources

Code that is safe to call by multiple threads simultaneously is called thread safe, i.e., it contains no race conditions.

Local variables

Primitives Since local primitive variables live entirely in thread's stack, they cannot be shared between threads and hence, are thread-safe.
Object references The reference itself is stored in the thread's stack and not shared. The object being reference however, is stored in the (shared) heap. If an
object which is instantiated locally never escapes the scope of the method, it is thread safe - which includes passing the object to other methods as long as
they do make the object accessible to other threads. The reference of LocalStuff is thread-safe in the example below. Only way its thread-safety can be
violated is if a method called with the reference as a local parameter stores it in a way that allows access to other threads.

public void method0() {


LocalStuff o = new LocalStuff();
o.setValue0("value zero");

method1(o);
}

public void method1(LocalStuff o) {


o.setValue1("value one");
}

Object member variables

Member variables are stored with the objects on the heap and hence are not thread-safe (when the same instance is shared among threads).

Thread Control Escape Rule

To check whether access to a piece of code is thread safe, the thread control escape rule can help:

If a resource is create, used and disposed within the control of the same thread, and never escapes the control of this thread, the use of that resource is thread
safe.

In addition, even if the use of an object is thread-safe, if that object points to a shared resource like a file, the application on the whole may not be thread-safe.

You might also like