Hi,
I just want to make sure that I understand this.
synchronized method is the same as synchronized block on "this":
same as
synchronized just crates lock on the supplied object, and makes sure that the block is executed only by one
thread (but of course if we have two instances it wouldn't work, because lock is on "this" instance.
so I would use synchronized block if I get object from a class I don't have access to. For example:
I inherited method getSth() which returns object, but I don't have access (cannot modify) to the class I inherit from, so I cannot change method getSth() to synchronized.
but now I have to make sure that all my classes that inherit from that class, put the "getSth()" in the synchronized block.
so in this case the block checks if any other thread is using the object returned by getSth(), if so, it waits till the thread finishes and after that starts the execution of the method. (this is valid only if the thread used object which have synchronized block, if it didn't then our thread can execute methods on this object simultaneously, because the previous thread didn't use any lock).
basically synchronized just creates/uses lock on the supplied argument, so if we use synchronized block for example on car object, we have to make sure that all our threads will have access to the car object through synchronized block (at least the methods we want to be synchronized), because it will check if there's any lock and if it is in use.
I'm not sure if I explained it well, but this is my understanding, so please let me know if it's correct.
Thanks