Some thoughts about sharing in Java-concurrent programming

Source: Internet
Author: User
Tags volatile

There are three ways to ensure concurrency security:

• Do not share

• Non-changeable

• Synchronization



The first two methods are relatively simple compared to the third type.

This article does not speak about language features and the associated synchronization mechanisms provided by the API, primarily documenting some thoughts about sharing.

Shared, it is simple to assume that multiple threads can access an object at the same time.

There is no synchronization problem if you are accessing only within a single thread.

Guaranteed single-threaded access to data is called thread confinement.



There are three ways to thread closure:

· Ad-hoc Thread Closure

• Stack closure

· ThreadLocal



Ad-hoc Thread Closure : Thread closure through program implementations, which means that we cannot use language attributes to enclose objects on a particular thread, which makes this way less reliable.


For example, suppose we guarantee that only one thread can write to a shared object, and that the object's read-modify-write (for example, a self-increment operation) will not have a condition in any situation.

If we add a volatile modifier to this object, we can guarantee the object's visibility, and any thread can read the object, but only one thread can write to it.

In this way, only through the thread closure +volatile decoration to properly guarantee its security, compared with the direct use of synchoronized decoration, although more suitable , but the implementation is slightly more complex .

This is the least recommended way to choose a thread closure.



Stack Closure : This approach is simpler to understand, and enclosing the execution thread as intrinsic to the local variable itself, enclosing it in the execution thread's stack, which the other threads cannot access.


For basic types of local variables, we don't have to think about anything, because the Java language feature itself guarantees that no method can get a reference to the base type.

For reference types of local variables, we need to pay a little attention to some problems to ensure that the stack is closed.

Refer to the following code to load the Ark, now we want to protect the animals, you need to ensure that the method's parameters, the calling of foreign methods, the return value will not be referenced to animals:

    public int loadtheark (collection<animal> candidates)  {         SortedSet<Animal> animals;         int numPairs = 0;        Animal  candidate = null;        animals = new  Treeset<animal> (New speciesgendercomparator ());         Animals.addall (candidates);        for  (Animal a :  animals)  {            if  ( candidate == null | |  !candidate.ispotentialmate (a))                  candidate = a;          & nbsp; else {                 ark.load (New animalpair (candidate, a));                 ++numPairs;                 candidate = null;             }        }         return numpairs;    }

First of all, the parameters of Loadtheark candidates, we have to filter its elements loaded into the Ark, the method after the end can not affect the ark of the animals and couples.

Secondly, we use the "kind sex comparator" to sort the animals, but it is a concrete, and there will be no uncertain behavior affecting the state of animals.

The last is the return value, obviously we want to report how many pairs of animals are loaded, the return type is a basic type and cannot be referenced by animals.

Well, this is a successful stack closure.



ThreadLocal: a kind of intimacy, which is almost a very common way, but also the most normative way.


We usually use threadlocal to ensure that mutable singleton variables and global variables are not shared by multithreading.

Let's just think about it. Using the Connection object to connect to the database in a single-threaded scenario, a global connection object is maintained throughout the application, given the initialization overhead of the connection object.

If we want to change this application to multithreading, since the connection object itself is not thread-safe, we need to thread it, and we can use threadlocal:

public class connectiondispenser {    static string db_url =   "Jdbc:mysql://localhost/mydatabase";    private threadlocal<connection>  connectionHolder            = new  Threadlocal<connection> ()  {                 public connection initialvalue ()  {                     try {                          return drivermanager.getconnection (Db_url);                     } catch  ( Sqlexception e)  {                         throw new runtimeexception ("unable to acquire  Connection, e ");                     }                 };            };     public connection getconnection ()  {         return connectionholder.get ();     }}

Not only is connection this scenario, if many of our operations frequently use an object, and we need to consider its thread closure and the overhead of its initialization, threadlocal is almost the best choice.

Although this looks a bit like a global map<thread,t>, in fact it can be understood, but its implementation is not so you understand.

Of course, this is convenient, but it does not mean that threadlocal can be abused, such as simply considering the concurrency security of the application to turn global variables into threadlocal.

This approach causes global variables to be difficult to abstract, to reduce their reusability, and to increase coupling.



This article is from the Alvez. -99.9% 0b/s "blog, be sure to keep this source http://alvez.blog.51cto.com/7711135/1549674

Some thoughts about sharing in Java-concurrent programming

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.