I'm at the beginning of a Java application. I've created a Service with some threads, but I haven't understood when I have to use synchronized and when not to.
For example, I have to connect with a bluetooth connection to a module, and then I use a Service with two threads: ConnectThread gives up the connection and ConnectedThread manages to read/write connection.
So when do I have to use synchronized?
Thank you
Thread synchronization is the concurrent execution of two or more threads that share critical resources. Threads should be synchronized to avoid critical resource use conflicts. Otherwise, conflicts may arise when parallel-running threads attempt to modify a common variable at the same time.
Synchronization in java is the capability to control the access of multiple threads to any shared resource. In the Multithreading concept, multiple threads try to access the shared resources at a time to produce inconsistent results. The synchronization is necessary for reliable communication between threads.
We need to synchronize the shared resources to ensure that at a time only one thread is able to access the shared resource. If an Object is shared by multiple threads then there is need of synchronization in order to avoid the Object's state to be getting corrupted. Synchronization is needed when Object is mutable.
Synchronized blocks provide granular control over a lock, as you can use arbitrary any lock to provide mutual exclusion to critical section code. On the other hand, the synchronized method always locks either on the current object represented by this keyword or class level lock, if it's a static synchronized method.
Use the Synchronized keyword whenever you different threads are using the same (i.e. a global) variables(s), basically when information is being shared. Check the code to see if this is the case.
Synchronized is not needed when the variables each thread is using is local. Using it then would result in loss in performance and can result in inconsistoncies.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With