This week's book giveaway is in the Mac OS forum. We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line! See this thread for details.
Hi, I am reading Kathy's book, chapter "Threads". The para written below is not clear. can any one help me out understanding this?? When you synchronize a method, the object used to invoke the method is the object whose lock must be acquired. But when you synchronize a block of code, you specify which object's lock you want to use as the lock, so you could, for example, use some third-party object as the lock for this pice of code. That gives you the ability to have more than one lock for code synchronization within a single object.
Is there any difference between method synchronization and block synchronization. This question is very important, because this question is being asked frequently in interviews :roll: . [ March 18, 2003: Message edited by: Tausif Khanooni ]
"Walking on water and building IT Architecture from <br />specification are easy if and only if both are frozen"
Static methods synchronize on the Class. Non-static methods synchronize on the object that the method is in. Blocks synchronize on any object you like. From another thread: Suppose you have several blocks of code in different methods in your class that you want to synchronize but not with each other. In other words, if you are in block1, I don't want anyone else in block1 but I don't care about someone else going into block2. If I synchronize on (this) the two blocks will be co-synchronized. A thread in one blocks the other. So instead I create two sempahore objects and use them. For example.
As always, great reply, Tom. A key point here is to realize that, when you define a method to be synchronized, the JVM automatically assumes that you want to lock on that object when the method is invoked. Therefore, is a process invokes a synchronized method of an object, no other process may invoke a synchronized object until the first process has finished and released the lock. However, when you have a synchronized block (a bit of code contained within a method, not the entire method), you get to pick which object you want to synchronize on. In other words, you get to pick your semaphore. You can choose to use 'this', if you'd like, making this lock equivalent to any synchronized methods. However, you can lock on any other object as well. If you choose to lock on some other object, one process could be within the synchronized block while another is in the synchronized block, like this: