Now, what would happen if both are used together
I would say nothing disastrous. Lets say we have threads A and B synchronized on common object. Thread A sleeps and then waits. They both will simply do nothing during sleep
and then as soon as wait
phase starts, the action resumes (in thread B). Probably such a combination might be even used for some fine-tuned thread orchestration, for example if you want to do some processing in thread B in some period of time (on the other hand, it would make much
more sense to put sleep()
in thread B in this case).
synchronization needs to be called at the method level of the object
Actually I am interested in this question myself. In fact I discovered recently that in C# it is not recommended
to declare public methods as synchronized (as well as using this
as a monitor lock, instead it is encouraged to use lock()
(which is equivalent to synchronized block in Java) on some other object whenever possible. The reason is simple. If you declare public non-static method as synchronized, somewhere else the object which has these methods might be used as a monitor lock itself. This can be quite confusing, one can easily "lose" the track of locks and end up in something terrible like deadlock.
I think the main idea is to keep things as simple for reviewers as possible. Sometimes synchronized methods are fine, in other situations it is better to introduce a dummy private object and use it as a monitor lock.