Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android, when I must use syncronized in a thread

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

like image 276
nani Avatar asked Jul 06 '15 13:07

nani


People also ask

When would thread synchronization is needed?

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.

Why would you add Synchronisation to your threads?

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.

Why do we need synchronized?

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.

Why would you want to use synchronized blocks instead of synchronized methods?

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.


1 Answers

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.

like image 123
Ramonster Avatar answered Oct 02 '22 04:10

Ramonster