How to use contemplate threadsafe to discover and determine Java concurrency problems

Source: Internet
Author: User
Tags final

It turns out that the benefits of multi-core hardware are difficult and risky. When using concurrency to write Java software correctly and securely, we need to think very carefully. Because error usage concurrency can lead to occasional defects that can even escape the most stringent test environments.

The static analysis tool provides a way to detect and fix concurrency errors before code executes. It can analyze the source code of the program or compile the bytecode before it is executed, and find the defect hidden in the code.

Contemplate's threadsafe solo is a commercially available eclipse static analysis plug-in designed specifically to detect and diagnose flaws hidden in Java programs. Because of the focus on concurrency flaws, Threadsafe is able to discover flaws that other commercial or free static analysis tools are not able to detect, and these tools often ignore the flaw or are not designed to look for the flaw at all. As far as we can ascertain, none of the other Java static analysis tools can capture any of the defects in the following samples.

In this article, I'll introduce Threadsafe through a series of concurrency flaws, both concrete samples and actual OSS code, showing the advanced static analysis of threadsafe and tight integration with eclipse so that we can Early detection and diagnosis of these deficiencies. If you want to experience Threadsafe on your code, you can download a free trial version on the contemplate site.

The concurrency flaw used as a sample in this article is caused by a developer not synchronizing access to shared data correctly. Such defects are also the most common form of concurrent defects in Java code and one of the most difficult to detect in code checking and testing. Threadsafe is able to detect numerous scenarios where synchronization is not used correctly, as described in this article, which also provides developers with critical contextual information to help diagnose the problem.

The original correct sync became incorrect over time.

If an instance of a class is invoked concurrently by multiple threads, then at design time, the developer must carefully consider how to concurrently access the same instance to ensure that it is handled correctly. Even if a good design is found, it is hard to guarantee that this carefully designed synchronization protocol will be fully respected in future additions to the code. Threadsafe can help point out these scenarios when the newly written code violates an existing concurrency design.

For simple synchronization Tasks, Java offers a number of different infrastructures, including synchronized keywords and more flexible java.util.concurrent.locks packages.

As a simple example, we use the Java built-in Synchronization facility to secure concurrent access to shared resources, and consider the following code fragment to implement the simulated "bank account" class.

public class BankAccount {

   protected final Object lock = new Object ();

   private int balance;

   protected int readbalance () {return
       balance;
   }

   protected void adjustbalance (int adjustment) {
       balance = balance + adjustment;
   }

   ... methods that synchronize on ' lock ' while calling
   //readbalance () or adjustbalance (..)

}

Developers of this class decide to provide access to the balance domain through two internal API methods, namely Readbalance () and Adjustbalance (). These methods are given the visibility of the protected level, so they may be accessed by BankAccount subclasses. Given that any outward-exposed specific operation on a BankAccount instance involves a series of complex calls to these methods, these methods should be executed as an atomic step, while the internal API method itself does not synchronize any. Instead, the callers of these methods synchronize the objects stored in the lock domain to ensure mutual exclusion and the atomicity of updates to the balance domain.

When the program is very small, the design of the program can be installed in a developer's mind, the risk of concurrent related issues is relatively small. However, in the actual project, the originally well-designed program needs to be extended to accommodate the new functionality, which is usually done by the project's new engineers.

Now, suppose that after the initial code was written for some time, another developer wrote the BankAccount subclass to add some new optional features. Unfortunately, the new developer does not necessarily understand the synchronization mechanism designed by the previous developer, and he does not realize that readbalance () and adjustbalance can not be invoked if the objects in the lock domain are not synchronized beforehand (..) Of

The BankAccount subclass code written by the new engineer might look like the following:

public class Bonusbankaccount extends BankAccount {

    private final int bonus;

    Public bonusbankaccount (int initialbalance, int bonus) {
        super (initialbalance);

        if (Bonus < 0)
            throw new IllegalArgumentException ("bonus must be >= 0");

        This.bonus = bonus;
    }
public void Applybonus () {
        adjustbalance (bonus);
    }
}

There are problems in the implementation of Applybonus (). In order to properly follow the synchronization policy for the BankAccount class, Applybonus () should synchronize lock when calling Adjustbalance (). However, there is no synchronization, so the author of Bonusbankaccount introduces a serious concurrency flaw here.

Although this flaw is serious, it is difficult to detect it in the test and even in the production phase. This flaw is manifested as an inconsistent account balance because a lack of synchronization can cause a thread to update the balance domain to other threads that are not visible. This flaw does not cause the program to crash, but silently produces inconsistent results in a way that is difficult to track. On the Quad core hardware, an attempt is made to return and lend to the same account concurrently with four threads, and 11 of the 40,000 transactions will fail.

Threadsafe can be used to identify concurrency defects similar to those introduced by the Bonusbankaccount class. The Eclipse plug-in running Threadsafe on the two classes mentioned above produces the following output:

See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/Java/

Related Article

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.