Java Concurrency Programming-the 2nd chapter-Thread Safety

Source: Internet
Author: User

Java Concurrency Programming-the 2nd chapter-Thread Safety

2. Thread Safety

2.1 What is thread safety

Thread-Safe classes: When a class is accessed by multiple threads, how these threads are executed alternately, regardless of how they are dispatched in the running environment, does not require the amount of synchronization or synergy in the code portion of the call. This class is a thread-safe class

Thread-safe classes encapsulate any needed synchronization so, clients need not provide their own.

2.1.1. Example:a Stateless Servlet

Stateless objects is always thread-safe.

2.2 atomicity

In a stateful servlet, the state variable count is ++count this should be an atomic operation under multi-threaded conditions

The possibility of incorrect results in the presence of unlucky timing are so important in concurrent programming that it H As a name:a race condition.

2.2.1 Race condition

How to produce: a race condition occurs when a correct result depends on the timing of the alternating execution of multiple threads

To make judgments or perform a calculation based on an observation that may fail.

Most common types: first detection after Execution (check-then-act) (Starbucks AB Meet friends example)

2.2.2 Example: Race condition for deferred initialization

Lazyinitrace If you apply the registry to the application, you may lose registration information, or perform inconsistent views on the same set of registered objects

@NotThreadSafe

public class Lazyinitrace {

Private Expensiveobject instance = null;

Public Expensiveobject getinstance () {

if (instance = = null)

Instance = new Expensiveobject ();

return instance;

}

}

Unsafesequence if the application is in persisted data, it will produce different objects with the same ID, violating the IDENTITY integrity constraints

@NotThreadSafe

public class Unsafesequence {

private int value;

/** Returns a unique value. */

public int GetNext () {

return value++;

}

}

2.2.3 Compound operation

Like ++count, this "read-modify-write" operation is collectively called a composite operation, and the composite operation should be atomic.

1, through the 2.3 lock mechanism

2. Using the existing thread-safe class Atomiclong

Listing 2.4. Servlet that Counts requests Using Atomiclong.

@ThreadSafe

public class Countingfactorizer implements Servlet {

Private final Atomiclong count = new Atomiclong (0);

Public long GetCount () {return count.get ();}

public void Service (ServletRequest req, Servletresponse resp) {

BigInteger i = extractfromrequest (req);

biginteger[] factors = factor (i);

Count.incrementandget ();

Encodeintoresponse (resp, factors);

}

}

Where practical, use existing Thread-safe objects, like Atomiclong, to manage your class ' s state. It's simpler to reason on the possible states and state transitions for existing thread-safe objects than it's for AR Bitrary state variables, and this makes it easier to maintain and verify thread safety.

In practice, use existing thread-safe classes to manage the state of a class whenever possible

2.3 Plus lock mechanism

Example: Unsafecachingfactorizer

To preserve state consistency, update related state variables in a single atomic operation

In order to maintain state consistency, you need to update all related state variables in an atomic operation

2.3.1 Built-in lock

Java provides built-in locking mechanism to support atomicity: the synchronized block

These built-in locks is called intrinsic locks or monitor locks

2.3.2 Re-entry

A thread can obtain a lock that is already held

2.4 Using locks to protect status

For all mutable states, it is necessary to use the same lock to protect

If all methods are synchronized, it can cause active and performance problems

2.5 Activity and performance

Network or console I/O. Do not hold locks

3. Sharing of objects

Java Concurrency Programming-the 2nd chapter-Thread Safety

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.