How it works...

The key to this example is in the Account class. In this class, we declared an AtomicLong variable named balance to store the balance of the account, a LongAdder variable named operations to store the number of operations we made with the account, and a DoubleAccumulator variable named commission to store the value of the commissions of the operations. In the constructor of the commission object, we specified that the value will be incremented with the expression 0.2*y. With this, we wanted to specify that we will increment the actual value of the variable with the result of its multiplication by 0.2 and the value of the parameter we pass to the accumulate() method.

To implement the getBalance() method that returns the value of the balance attribute, we used the get() method of the AtomicLong class. To implement the getOperations() method that returns a long value with the number of operations, we used the longValue() method. To implement the getCommission() method, we used the get() method of the DoubleAccumulator class. To implement the setBalance() method that establishes the value of the balance attribute, we used the set() method of the AtomicLong class.

To implement the addAmount() method that adds an import to the balance of the account, we used the getAndAdd() method of the AtomicLong class that returns the value and increments it by the value specified as a parameter. We also used the increment() method of the LongAdder class that increments the value of the variable by one and the accumulate() method of the DoubleAccumulator class to increment the value of the commission attribute following the specified expression. Take into account that the addAmount() method is not atomic as a whole although it calls three atomic operations.

Finally, to implement the subtractAmount() method that decrements the value of the balance attribute, we used the getAndAdd() method. We also included calls to the increment() and accumulate() methods of the LongAdder and DoubleAccumulator classes.

Then, we implemented two different tasks:

  • The Company class simulates a company that increments the balance of the account. Each task of this class makes 10 increments of 1,000 each.
  • The Bank class simulates a bank where the proprietary of the bank account takes out its money. Each task of this class makes 10 decrements of 1,000 each.

In the Main class, you created an Account object with a balance of 1,000. Then, you executed a bank task and a company task so the final balance of the account is the same as the initial one.

When you execute the program, you will see how the final balance is the same as the initial one. The following screenshot shows the output of an execution of this example:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.199.191