I\'v been coming to drawing graphics in Android. There\'s a lot of sample applications out there, but one thing I always seeing is lockCanvas. Can someone explain it closer
synchronized
indicates that only one thread can execute that block of code at a time.
In this example, without the synchronized
block, multiple threads could draw graphics at the same time, and the results could be messy. Thus, synchronized
ensures that only one thread can draw at a time.
lockCanvas()
creates a surface area that you will write to. The reason it's called lockCanvas()
is because until you call unlockCanvasAndPost()
no other code can call lockCanvas()
and write to the surface until your code is finished.
In general, locks are important to understand, specifically when it relates to multithreaded programming. A lock is a synchronization primitive that is used to guard against simultaneous accessing of resources/code by multiple threads. It gets it's name because it behaves much like a physical lock. Generally one thread can obtain a lock, and until it releases the lock, no other thread can obtain the lock. One potential gotcha to using a lock is that misuse of it can lead to a "dead lock" situation, where threads are left waiting for the lock, and it's never released.