When do I synchronize methods or use synchronized blocks in my methods in an Android game?
Asked Answered
M

1

11

I'm looking into writing simple graphics code in Android and I've noticed some synchronized() blocks.

What is the reasoning behind this and how do I know when I should be "synchronizing" my code?

Minny answered 14/3, 2010 at 0:46 Comment(0)
Y
26

synchronized statement blocks are commonly used in concurrent programming (multithreaded applications), where your application utilizes many threads. As an example for an Android game, you could have one thread with client processing, other for the server, one to spawn other processes, etc.

The keyword itself ensures that your methods will be accessed one thread at a time, which makes them thread-safe. If your application were to share resources without using synchronized statements, you run the risk of deadlock occurring.

Deadlock will result in a hang-up, i.e. the process hangs up. Deadlock should be avoided at all cost especially dealing with the size of processor of a mobile phone.

Yingyingkow answered 14/3, 2010 at 1:45 Comment(1)
Deadlocks can't happen without thread synchronization (of which using synchronized is the simplest method, but not the only one). And the size (or speed) of processor doesn't matter for a deadlock. The number of cores might (but that was not yet something people had to worry about in 2010).Ur

© 2022 - 2024 — McMap. All rights reserved.