Java concurrent Programming-thread closure

Source: Internet
Author: User

There are three ways to ensure concurrency security:

Not shared, immutable, synchronized

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 :

This approach is less reliable because the program implements thread closure, which means that we cannot use language attributes to enclose objects on a particular thread.

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 relatively simple to understand, closed in the execution of the thread is the intrinsic nature of the local variable itself, closed in the execution thread of the stack, other threads can not access it for granted.

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:

123456789101112131415161718     publicintloadTheArk(Collection<Animal> candidates) {        SortedSet<Animal> animals;        intnumPairs = 0;        Animal candidate = null;        animals = newTreeSet<Animal>(newSpeciesGenderComparator());        animals.addAll(candidates);        for(Animal a : animals) {            if(candidate == null || !candidate.isPotentialMate(a))                candidate = a;            else{                ark.load(newAnimalPair(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:

It's almost a very common way, and it's the most canonical way to give people a sense of intimacy.

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:

123456789101112131415161718 publicclassConnectionDispenser {    staticString DB_URL = "jdbc:mysql://localhost/mydatabase";    privateThreadLocal<Connection> connectionHolder            newThreadLocal<Connection>() {                publicConnection initialValue() {                    try{                        return DriverManager.getConnection(DB_URL);                    catch(SQLException e) {                        thrownewRuntimeException("Unable to acquire Connection, e");                    }                };            };    publicConnection 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.

Java concurrent Programming-thread closure

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.