Thread Safety and Shared Resources

转载 2011年10月14日 17:29:27

Thread Safety and Shared Resources


Code that is safe to call by multiple threads simultanously is called thread safe. If a piece of code is thread safe, then it contains no race conditions. Race condition only occur when multiple threads update shared resources. Therefore it is important to know what resources Java threads share when executing.

Local Variables

Local variables are stored in each thread's own stack. That means that local variables are never shared between threads. That also means that all local primitive variables are thread safe. Here is an example of a thread safe local primitive variable:

public void someMethod(){
  long threadSafeInt = 0;


Local Object References

Local references to objects are a bit different. The reference itself is not shared. The object referenced however, is not stored in each threads's local stack. All objects are stored in the shared heap. If an object created locally never escapes the method it was created in, it is thread safe. In fact you can also pass it on to other methods and objects as long as none of these methods or objects make the passed object available to other threads. Here is an example of a thread safe local object:

public void someMethod(){
  LocalObject localObject = new LocalObject();


public void method2(LocalObject localObject){

The LocalObject instance in this example is not returned from the method, nor is it passed to any other objects that are accessible from outside the someMethod() method. Each thread executing the someMethod() method will create its own LocalObject instance and assign it to the localObject reference. Therefore the use of the LocalObject here is thread safe. In fact, the whole method someMethod() is thread safe. Even if the LocalObject instance is passed as parameter to other methods in the same class, or in other classes, the use of it is thread safe. The only exception is of course, if one of the methods called with the LocalObject as parameter, stores the LocalObject instance in a way that allows access to it from other threads.

Object Members

Object members are stored on the heap along with the object. Therefore, if two threads call a method on the same object instance and this method updates object members, the method is not thread safe. Here is an example of a method that is not thread safe:

public class NotThreadSafe{
    StringBuilder builder = new StringBuilder();
    public add(String text){

If two threads call the add() method simultanously on the same NotThreadSafe instance then it leads to race conditions. For instance:

NotThreadSafe sharedInstance = new NotThreadSafe();

new Thread(new MyRunnable(sharedInstance)).start();
new Thread(new MyRunnable(sharedInstance)).start();

public class MyRunnable implements Runnable{
  NotThreadSafe instance = null;
  public MyRunnable(NotThreadSafe instance){
    this.instance = instance;

  public void run(){
    this.instance.add("some text");

Notice how the two MyRunnable instances share the same NotThreadSafe instance. Therefore, when they call the add() method on the NotThreadSafe instance it leads to race condition.

However, if two threads call the add() method simultanously on different instances then it does not lead to race condition. Here is the example from before, but slightly modified:

new Thread(new MyRunnable(new NotThreadSafe())).start();
new Thread(new MyRunnable(new NotThreadSafe())).start();

Now the two threads have each their own instance of NotThreadSafe so their calls to the add method doesn't interfere with each other. The code does not have race condition anymore. So, even if an object is not thread safe it can still be used in a way that doesn't lead to race condition.

The Thread Control Escape Rule

When trying to determine if your code's access of a certain resource is thread safe you can use the thread control escape rule:

If a resource is created, 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.

Resources can be any shared resource like an object, array, file, database connection, socket etc. In Java you do not always explicitly dispose objects, so "disposed" means losing or null'ing the reference to the object.

Even if the use of an object is thread safe, if that object points to a shared resource like a file or database, your application as a whole may not be thread safe. For instance, if thread 1 and thread 2 each create their own database connections, connection 1 and connection 2, the use of each connection itself is thread safe. But the use of the database the connections point to may not be thread safe. For example, if both threads execute code like this:

check if record X exists
if not, insert record X

If two threads execute this simultanously, and the record X they are checking for happens to be the same record, there is a risk that both of the threads end up inserting it. This is how:

Thread 1 checks if record X exists. Result = no
Thread 2 checks if record X exists. Result = no
Thread 1 inserts record X
Thread 2 inserts record X

This could also happen with threads operating on files or other shared resources. Therefore it is important to distinguish between whether an object controlled by a thread is the resource, or if it merely references the resource. 

线程安全和资源共享(Thread Safety and Shared Resources)

  • shfqbluestone
  • shfqbluestone
  • 2015年05月28日 23:36
  • 709

Thread Safety

thread safe
  • wwq518
  • wwq518
  • 2016年03月12日 15:46
  • 415

Java Thread-safe http://jcip.n...
  • samfang
  • samfang
  • 2013年04月11日 08:25
  • 1044

Thread safety
  • a19576
  • a19576
  • 2013年07月03日 15:46
  • 329

Thread Safe(线程安全)和None Thread Safe(NTS,非线程安全)之分

Windows版的PHP从版本5.2.1开始有Thread Safe(线程安全)和None Thread Safe(NTS,非 线程安全)之分,这两者不同在于何处?到底应该用哪种?这里做一个简单的...
  • kongdeqian1988
  • kongdeqian1988
  • 2012年08月29日 13:36
  • 11886

如何判断PHP 是线程安全还是非线程安全的

什么是线程安全与非线程安全? 线程安全就是在多线程环境下也不会出现数据不一致,而非线程安全就有可能出现数据不一致的情况。 线程安全由于要确保数据的一致性,所以对资源的读写进行了控制,换句话说增加...
  • aoyoo111
  • aoyoo111
  • 2014年02月09日 23:29
  • 14321

ubuntu 15.10 安装matlab2014b

  • zhouzhouzf
  • zhouzhouzf
  • 2016年04月10日 19:15
  • 1530

boost::shared_ptr Thread Safety

"read" (accessedusing only const operations) simultaneously by multiple threads:  OK "written to" (...
  • lingqinghua
  • lingqinghua
  • 2011年11月29日 16:22
  • 696

XAMPP 1.7.4 Thread Safety的debug调试

部分摘自最近使用xampp 1.7.4,原来在调试的时候,...
  • jallin2001
  • jallin2001
  • 2011年07月06日 16:10
  • 4491

Thread Safety Summary

Thread Safety Summary This appendix describes the high-level thread safety of some key frameworks i...
  • u014544346
  • u014544346
  • 2016年04月13日 23:09
  • 191
您举报文章:Thread Safety and Shared Resources