is the following statement correct:
" There shouldn't be any thread interference between two synchronized methods in 2 different classes . So they can run concurrently without any problems."
Thanks for your time
is the following statement correct:
" There shouldn't be any thread interference between two synchronized methods in 2 different classes . So they can run concurrently without any problems."
Thanks for your time
You misunderstood the concept a little bit. Collisions happen when two (or more) threads simultaneously try to make a change on the same data or when one of them tries the read the data while the other thread is trying to change it.
When two thread tries to change the shared resource simultaneously, a race condition occurs. Check out this link to learn more about Race Condition.
In order to prevent this kind of problems, you need to guard the shared resource for simultaneous changes. Mutexes and semaphores are invented for this purpose: To lock the shared resource for the other threads, when one thread is currently making a change on it. For this purpose, Java uses the synchronized keyword. You can read more about Synchronized in Java using the link.
Note that, using the synchronized keyword will not eliminate all of the synchronization related issues, but it is a good starting point.
That is way too vague. A few pointers:
"how does synchronization work in Java": There are a couple of mechanisms, the question seems to be about the synchronized
keyword. This works by marking "critical sections" that must not be executed by more than one thread at the same time, and having the threads "lock" a monitor object while they are in that section (so that all other threads wait).
synchronized
methods synchronize on the object instance (or class object in case of a static method). So methods in different classes do not synchronize with each-other that way. They will run concurrently.
you can use the synchronized
keyword to synchronize blocks on any other monitor object. This way, methods in different classes can still be synchronized with each-other.
"can run concurrently without problems" is not guaranteed just by having some synchronization (or lack thereof). You need to see what mutable state these methods (directly or indirectly) try to access (and who else does the same) to see what kind of concurrency control is necessary.