java concurrency of the thread-safety issues

Concurrency (concurrency) is not a strange word, simply put, is cpu perform multiple tasks at the same time.

The Java Concurrency by multithreading implementation.

Jvm in the world, just as irrelevant parallel thread space, a serial in a virtual machine. (Of course, this is a more general term interaction between threads can be, they are not necessarily serial.)

Multithreading existence is press cpu, improve application performance, but also reduce certain design complexity (with a realistic time thinking design program).

Multithreading will lead to many problems difficult to avoid, such as overhead deadlock, dirty, thread management, and so on. It will greatly increase the complexity of programming.

 

Deadlock and dirty data is a typical thread-safety issues.

In simple terms, the security thread is this:  In a multithreaded environment, can never guarantee program correctness.

Only the presence of shared data when you need to consider thread safety issues. 

 

Solve thread safety issues:

How to solve really is the focus of the process. Currently solved in three ways:

First, modify threading model. That is not the state variable shared among threads. Generally this change is relatively large, we need to do what.

Second, the object becomes immutable objects. Sometimes fail to realize.

Third, it is more common, and the use of synchronization when accessing state variables. synchronized and Lock can be synchronized. Simply put, that is, when you access or modify a variable locking state, exclusive objects, so that other threads to enter.

It would be a way to isolate the thread. (In this way, there are many shortcomings, such as deadlock, performance issues, etc.)

 

In fact, there is a better way is to design a thread-safe class. "Code Complete" mentioned there, the sooner the problem is solved, the less the cost it takes.

Yes, in the design, consider thread safety issues will be much easier.

First consider whether the class will exist in a multithreaded environment. If not, the thread is not considered safe.

Then consider whether the class can be designed as an immutable object, or the fact that immutable objects. If so, is not considered thread-safe

Finally, the process to design a thread-safe class.

Design thread-safe class process:

1, identify all variables including the state of the object.

2, identify the invariance conditions constrained state variables.

3, concurrent access management policy established state of the object.

Guess you like

Origin www.cnblogs.com/duguangming/p/11404575.html