Thread Safety and Shared Resources

Source: Internet
Author: User
Thread Safety and Shared Resources

Code 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 is multiple threads update shared resources. Therefore it is important to know what resources Java threads when share. Local Variables

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

public void SomeMethod () {
  
  long threadsafeint = 0;

  threadsafeint++;
}
Local Object References

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

public void SomeMethod () {
  
  Localobject localobject = new Localobject ();

  Localobject.callmethod ();
  METHOD2 (Localobject);
}

public void Method2 (Localobject localobject) {
  localobject.setvalue ("value");
}

The Localobject instance in this example isn't returned from the method, nor are it passed to no other than objects that AR e accessible from outside to SomeMethod () method. Each thread executing the SomeMethod () method would create its own Localobject instance and assign it to the Localobject re Ference. Therefore the use of the Localobject this is thread safe. In fact, the whole method SomeMethod () is thread safe. Even if the Localobject instance is passed as parameter into other methods in the same class, or in other classes, the use O F It is thread safe. The only exception was of course, if one of the methods called with the Localobject as parameter, stores the Localobject in Stance in a way which allows access to it from the 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 Not thread safe. This is a example of ' a ' is ' not ' thread safe:

public class notthreadsafe{
    StringBuilder builder = new StringBuilder ();
    
    Public Add (String text) {
        this.builder.append (text);
    }	
}

If Two threads call the "Add () method" simultanously on the same Notthreadsafe instance then it leads to race Condi tions. 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. 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 leads to RAC E condition. The example from before, but slightly modified:

New Thread (New Myrunnable Notthreadsafe ()). Start ();
New Thread (New Myrunnable Notthreadsafe ()). Start ();

Now the two threads have their own instance of Notthreadsafe so their to the "Add method" calls ' t doesn with each other. The code does not have race condition anymore. So, even if it isn't thread safe it can still be used in a way that doesn ' t leads to race condition. The Thread control Escape rule

When trying to determine if your code's access of a certain resource is thread safe and 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 O F This thread, the "use of
" resource is thread safe.

The resources can is any shared resource like an object, array, file, database connection, socket etc. In Java you don't always explicitly dispose objects, so "disposed" means losing or null ' ing "the object.

Even if is thread safe, if that object points to a shared resource like a file or database, your APPL Ication as a whole may is 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" is 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 the happens A risk that both to the threads end up inserting it. This are how to:

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 and threads operating on files and 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.


Http://tutorials.jenkov.com/java-concurrency/thread-safety.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.