<title></title> Reprinted from: https://samxiangyu.wordpress.com/2015/02/20/java-concurrency-guardedby/ Java Concurrency: @GuardedBy
When reading Downloadservice class in Android Open Source Project, I noticed a use of @GuardedBy annotation, whic H is kind of the like synchronized keyword in Java but with alternative locks. We may use the This annotation as:
| 1234 |
publicclass foo { @GuardedBy("this") publicString str;} |
As we can see, the usage is @GuardedBy (lock) which means the guarded fields or methods can being accessed by some Thread only if the thread is holding the lock. We can specify the lock to the following types:
- this: The intrinsic lock of the object in whose class, the field is defined.
- class-name.this : For inner classes, the It may is necessary to disambiguate ' this '; The class-name.this designation allows you to specify which "this" reference is intended
- itself : for reference. The object to which the field refers.
- field-name : The Lock object is referenced by the (instance or static) field specified by Field-name.
- class-name.field-name : The Lock object is reference by the static field specified by Class-name.field-name.
- method-name () : The lock object is returned by calling the named Nil-ary method.
- Class-name.class : The class object for the specified class should is used as the lock object.
An example:
| 123456 |
< Code class= "Java keyword" >public class BankAccount { &NBSP;&NBSP; private object credential = new object (); &NBSP;&NBSP; @GuardedBy ( "credential" &NBSP;&NBSP; private int amount; |
In the code snippet above, amount can is accessed when someone have got the synchronization lock of credential, so amount I n A BankAccount is guarded by the credential. Let's add something to the This class.
| 123456789 |
public class BankAccount { private Object credential = new Object(); @GuardedBy("credential") private int amount; @GuardedBy("listOfTransactions") private List<Transaction> listOfTransactions;} |
We are now having a list of transactions in the BankAccount. The list object has many elements so, it has references to all of the elements in the list. Here we use @GuardedBy ("Listoftransactions") to specify, the lock is associated with the objects which listof Transactions refers to. In other words, someone must hold locks of the "the" and "order to" the lock of this List object.
Java Concurrency: @GuardedBy