If a class has both synchronized and non-synchronized methods, multiple threads can still access the class's non-synchronized methods!
I wasn't sure whether that meant that you can still access the unsynchronized methods even if another thread has the object's lock. I wrote the following code to find out:
The out put I get is:
I'm taking this to mean that:
1. The Thread called 'one' starts the run method and enters the synchronized block where it aquires the lock to the LockTest instance.
2. It executes the for loop until i == 100 and then sleeps. *But it still has the lock*
3. Because the Thread one is sleeping, and dispite the fact that Thread one has the lock, the 'main' thread can still access the *unsynchronized* printStuff() method of the LockThis instance, so it is allowed to execute the for loop in the main method.
4. Thread one wakes up and finishes executing the run() method and releases the lock on the LockTest object.
Does everyone else agree that this is what is happening?
Sure, but your example lacks synchronized methods. Your synchronization is on block-level, I'm not sure why you don't declare the run method as synchronized. Of course, I don't think it would change anything ; - )
Censorship is the younger of two shameful sisters, the older one bears the name inquisition. -- Johann Nepomuk Nestroy
Locks scenario comes only when a particular thread has to run a synchorized method on a particular object, otherwise in case of non-synchronized method ,thread dnt care for locks on the objects !!!
SCJP 6.0 96%
(Connecting the Dots ....)
Joined: Oct 24, 2008
I synchronized a block rather than a method for no other reason than... just because. And I need to learn the syntax. I'm not sure how synchronized blocks are used in practice, but as the lock was still on the 'this' object it doesn't make a difference to what I wanted to find out.
Thanks for your replies, I appreciate it.
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com
subject: Can you still access an unsnychronized method even when there is a lock on the object?