简体   繁体   中英

How do I know when a method can be called safely from a background thread?

I understand that many Android SDK methods must be called on the main thread. This is usually documented in places like https://developer.android.com/topic/performance/threads#references . Is there a way to tell for sure that a method can be safely called from a background thread in a generic manner? Some libraries do not document this, and it's not trivial to know the answer when deciding to offload work from the main thread to another thread.

One answer came from the documentation you linked itself:

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.

In other words, DO NOT mess with anything that interacts with the main thread almost all of the time.

Another answer would be is to make sure that the documentation tell you that an Object is thread-safe .

Something like a StringBuilder is not thread-safe, but it's brother the StringBuffer is.

Thread safe means that just the one thread is modifying the data alone, one thread at a time.


An example of a thread safe method is a method that returns a final variable.

Something like this:

private final String location="Somewhere in the world?";
public String getLocation(){
  return location;
}

You can also make some situations that are not thread-safe the opposite using synchronization .

Synchronizing makes only one thread can access an object at a time.

The volatile keyword acts like the synchronized keyword.

All it does is make every thread know that a value has been changed, hence all objects pointing to the modified data is updated.


TL;DR

Find attributes that makes you think that a method is thread-safe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM