开发者

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

开发者 https://www.devze.com 2022-12-23 07:40 出处:网络
I\'m looking into writing simple graphics code in Android and I\'ve noticed some s开发者_运维问答ynchronized() blocks.

I'm looking into writing simple graphics code in Android and I've noticed some s开发者_运维问答ynchronized() blocks.

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号