Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Wiki Markup
Synchronization is more expensive than using the optimized {{java.util.concurrent}} utilities and should only be used when the utilities do not contain the required method to carry out the atomic operation. When using explicit synchronization, the programmer must also ensure that two or more threads are not mutually accessible from a different set of two or more threads such that each thread holds a lock while trying to obtain another lock that is held by the other thread \[[Lea 00|AA. Java References#Lea 00]\]. Failure to follow this advice results in deadlocks ([CON11-J. Avoid deadlock by requesting locks in the proper order]).

Compliant Solution (

...

3)

Constructors and methods can make use of an alternative representation called block synchronization which synchronizes a block of code rather than a method, as highlighted below.

...

Block synchronization is preferable because it reduces the period for which the lock is held. The variable itemsInInventory still needs to be declared volatile because the check to determine whether it is greater than 0 relies on the latest value of the variable. An alternative to avoid the need to declare the variable volatile is to use block synchronization across the whole if-else block. However, this solution is more costly.

Risk Assessment

...