时间:2021-07-01 10:21:17 帮助过:4人阅读
When reading DownloadService class in Android Open Source Project, I noticed a use of @GuardedBy annotation, which is kind of like synchronized keyword in Java but with alternative locks. We may use this annotation as:
1234 | public class foo { @GuardedBy ( "this" ) public String str; } |
As we can see, the usage is @GuardedBy(lock) which means the guarded fields or methods can be accessed by some thread only when the thread is holding the lock. We can specify the lock to the following types:
An example:
123456 | public class BankAccount { private Object credential = new Object(); @GuardedBy ( "credential" ) private int amount; } |
In the code snippet above, amount can be accessed when someone has got the synchronization lock of credential, so amount in a BankAccount is guarded by the credential. Let’s add something to this class.
123456789 | public class BankAccount { private Object credential = new Object(); @GuardedBy ( "credential" ) private int amount; @GuardedBy ( "listOfTransactions" ) private List<Transaction> listOfTransactions; } |
We now have a list of Transactions in the BankAccount. The List object has many elements so that it has references to all the elements in the list. Here we use @GuardedBy(“listOfTransactions”) to specify that the lock is associated with the objects which listOfTransactions refers to. In other words, someone must hold locks of all the Transactions in order to hold the lock of this List object.
Java concurrency : @GuardedBy
标签: