Andy Yu wrote:Hi guys,
Reading the 'inside the java virtual machine' which said 'Once a thread owns a lock, it can request the same lock again
multiple times, but then has to release the lock the same number of times before it is made available to other threads'
just make me confused,and i cannot feature out why it does like that ,any special reasons for that ?
could any body tell me ?
thanks for any hint!
Example. Let's say you want to write some sort of thread safe data structure (with some processing capability). It has getters -- which has to be synchronized because it may be called from multiple threads. Furthermore, let's say that the getters are very complex, as it has to do a lot of calculations while getting the data. In other words, these getters aren't getting data held simply in instance variables.
Now, let's say you want lot of different processors too. And these processors also need to be synchronized as it may be called by multiple threads.... Question. Let's say a processor method want to get the data (so it can process it of course), How would it do it? Well, it can call the getters !! ... but how would you do that? Your processor already owns the lock, and calling the getter will try to get the lock again. Luckily, you can just have your processor call the getter, as Java allows you to acquire the same lock multiple times.
It can get way more complex. Getters can call other getters. Processors can call other processors, in addition to getters. Heck, processors can even recursively call itself, if needed. And every synchronized method just acquires the lock one more time on entry, and release it one time on exit. No need to track locks from synchronized method call to synchronized method call, the JVM is handling it for you.
Henry