Concurrent set (8) use atomic variables

Source: Internet
Author: User
Disclaimer: This article is the first chapter of Java7ConcurrencyCookbook. Author: javierfernándezgonz ález Translator: Zheng Yuting proofreaders: Fang tengfei introduced atomic variables in Java1.5, it provides atomic operations on a single variable. When you are operating on a common variable, every operation you implement in Java will be

Disclaimer: This article is the first chapter of Java 7 Concurrency Cookbook. Author: Javier Fernández Gonz ález Translator: Zheng Yuting Proofreader: fang tengfei introduced atomic variables in Java 1.5, which provide atomic operations on a single variable. When you are operating on a common variable, every operation you implement in Java will be

Disclaimer: This article is the first chapter of Java 7 Concurrency Cookbook. Author: Javier Fernández Gonz ález Translator: Zheng Yuting Proofreader: Fang tengfei

An atomic variable is introduced in Java 1.5, which provides atomic operations on a single variable. When you are operating on a common variable, every operation you implement in Java will be converted into several machine-readable commands during program compilation. For example, when you assign a value to a variable, you only use one command in Java, but when you compile this program, this command is converted into multiple JVM language commands. In this way, when you operate multiple threads and share a variable, data inconsistency will occur.

To avoid this problem, Java introduces atomic variables. When a thread is operating on an atomic variable, even if other threads want to operate on the variable, the implementation of the class contains a mechanism to check whether the operation is complete. Basically, the operation gets the value of the variable, changes the value of the local variable, and then tries to replace the old value with a new value. If the old value is the same, change it. If not, start the operation again. This operation is called Compare and Set ).

Atomic variables do not use any locks or other synchronization mechanisms to protect access to their values. All of their operations are based on CAS. It ensures that several threads can operate on an atomic object at the same time without data inconsistency errors, and its performance is better than normal variables protected by the synchronization mechanism.

In this guide, you will learn how to use atomic variables to implement a bank account and two different tasks: one saving money to the account and the other extracting money from the account. In the example, you will use the AtomicLong class.

Preparation

The example in the Guide is implemented using Eclipse IDE. If you use Eclipse or other IDE such as NetBeans, open and create a new java project.

How...

Follow these steps to implement the following example:
[Code language = 'java']
// 1. Create a class named Account to simulate a bank Account.
Public class Account {

// 2. Declare a private AtomicLong attribute named balance to store the account balance.
Private AtomicLong balance;

// 3. Implement the class constructor and initialize its property value.
Public Account (){
Balance = new AtomicLong ();
}

// 4. Implement a method named getBalance () to return the balance property value.
Public long getBalance (){
Return balance. get ();
}

// 5. Implement a method named setBalance () to set the balance property value.
Public void setBalance (long balance ){
This. balance. set (balance );
}

// 6. Implement a method named addAmount () to increase the balance attribute value.
Public void addAmount (long amount ){
This. balance. getAndAdd (amount );
}

// 7. Implement a method named substractAmount () to reduce the balance attribute value.
Public void subtractAmount (long amount ){
This. balance. getAndAdd (-amount );
}

// 8. Create a class named and implement the Runnable interface. This class simulates the company's payment.
Public class Company implements Runnable {

// 9. Declare a private Account attribute named account.
Private Account account;

// 10. Implement the class constructor and initialize its property value.
Public Company (Account account ){
This. account = account;
}

// 11. Implement the run () method of the task. Use the addAmount () method of the account to increase its balance 10 times, with an increase of 1000.
@ Override
Public void run (){
For (int I = 0; I <10; I ++ ){
Account. addAmount (1000 );
}
}

// 12. Create a class named Bank and implement the Runnable interface. This class simulates withdrawals from an account.
Public class Bank implements Runnable {

// 13. Declare a private Account attribute named account.
Private Account account;

// 14. Implement the class constructor and initialize its property value.
Public Bank (Account account ){
This. account = account;
}

// 15. Implement the run () method of the task. Use the subtractAmount () method of the account to reduce its balance by 10 times. The decrease is 1000.
@ Override
Public void run (){
For (int I = 0; I <10; I ++ ){
Account. subtractAmount (1000 );
}
}

// 16. Create an example of the Main class by creating a class named main and adding the Main () method.
Public class Main {

Public static void main (String [] args ){

// 17. Create an Account object and set its balance to 1000.
Account account = new Account ();
Account. setBalance (1000 );

// 18. Create a new Company task and a thread to run it.
Company company = new Company (account );
Thread companyThread = new Thread (company );
// Create a new Bank t task and a thread to run it.
Bank bank = new Bank (account );
Thread bankThread = new Thread (bank );

// 19. Write the initial account balance on the console.
System. out. printf ("Account: Initial Balance: % d \ n", account. getBalance ());

// 20. Start the thread.
CompanyThread. start ();
BankThread. start ();

// 21. Use the join () method to wait for the end of the thread and write the final account balance to the console.
Try {
CompanyThread. join ();
BankThread. join ();
System. out. printf ("Account: Final Balance: % d \ n", account. getBalance ());
} Catch (InterruptedException e ){
E. printStackTrace ();
}
[/Code]

How does it work...

The key to this example is the Account class. In this class, we declare a AtomicLong attribute named balance to store the account balance. Then we use the method provided by the AtomicLong class to implement the method for operating the balance. To implement the getBalance () method and return the balance property value, you must use the get () method of the AtomicLong class. To implement the setBalance () method and set the balance value, you must use the set () method of the AtomicLong class. To implement the addAmount () method and add income to the balance value, you need to use the getAndAdd () method of the AtomicLong class, add it with a specific parameter value, and return the value. Finally, to implement the subtractAmount () method and reduce the balance value, you must also use the getAndAdd () method.

Then, you implement two different tasks:

The Company class simulates a Company and increases the balance value. Each task of this class will increase 10 times, and the increment value is 1000.
The Bank class simulates a Bank, and the Bank is charged as the account owner. Each task of this class will be reduced 10 times, and the decreasing value is 1000.

In the Main class, you have created an Account object with a balance of 1000. Then, you run a bank task and a company task, so the final account balance must be equivalent to the initial balance.

When you run the program, you can find that your final balance is the same as your initial value. The following is the output of the example running result:

More...

As we mentioned earlier, Java has other atomic classes. For example: AtomicBoolean, AtomicInteger, and AtomicReference.

See

Chapter 2, basic thread synchronization: synchronize a method

Original article address: Concurrent sets (8) use atomic variables. Thanks to the original author for sharing.

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.