I have a method updateFoo() of an activity called both from a Handler thread every 5 seconds and from a button when user want to press it... updateFoo update the interface of my activity... to make this method thread safe I declared it "synchronized" ... Is that the right way???
There is no rule that makes the code thread safe, the only thing you can do is make sure that your code will work no matter how many times is it being actively executed, each thread can be interrupted at any point, with each thread being in its own state/location, and this for each function (static or otherwise) that ...
By design, Android View objects are not thread-safe. An app is expected to create, use, and destroy UI objects, all on the main thread. If you try to modify or even reference a UI object in a thread other than the main thread, the result can be exceptions, silent failures, crashes, and other undefined misbehavior.
When an application component starts and the application does not have any other components running, the Android system starts a new Linux process for the application with a single thread of execution. By default, all components of the same application run in the same process and thread (called the "main" thread).
First of all, the answer is NO. The method is not thread-safe, because the counter++ operation is not atomic, which means it consists more than one atomic operations. In this case, one is accessing value and the other is increasing the value by one.
Well using a Handler : http://developer.android.com/reference/android/os/Handler.html is thread safe. You can look at a tutorial here : http://mindtherobot.com/blog/159/android-guts-intro-to-loopers-and-handlers/ I advice you to do long calculations in threads and the UI updates from the Handler (created in the main thread) call from your worker thread.
Marking a method synchronized
is a way to make it thread safe -- basically it makes it so that only one thread can be in the method at any given time.
However, that might not be the best option because if updateFoo()
does some long running operations, your UI thread could hang (ie. the button press might get stuck waiting to get into [and execute] updateFoo()
.
A more granular method would be to use locks, or some of Java's other threading options. If you post the code to your method, we'd be able to find a better solution.
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