Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make an android activity method thread safe

Tags:

android

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???

like image 796
Erenwoid Avatar asked May 02 '11 23:05

Erenwoid


People also ask

How do I make sure a method is thread-safe?

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 ...

What is thread-safe android?

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.

Is android single threaded?

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).

Are method calls thread-safe?

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.


2 Answers

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.

like image 145
dranfi Avatar answered Oct 12 '22 23:10

dranfi


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.

like image 35
debracey Avatar answered Oct 12 '22 22:10

debracey