天天看點

編寫線程安全的方法

Service和ContentProvider中的方法都要注意:線程安全,理由如下:

In some situations, the methods you implement might be called from more than one thread, and therefore must be written to be thread-safe.

This is primarily true for methods that can be called remotely—such as methods in a bound service. When a call on a method implemented in an 

IBinder

 originates in the same process in which the 

IBinder

 is running, the method is executed in the caller's thread. However, when the call originates in another process, the method is executed in a thread chosen from a pool of threads that the system maintains in the same process as the

IBinder

 (it's not executed in the UI thread of the process). For example, whereas a service's 

onBind()

 method would be called from the UI thread of the service's process, methods implemented in the object that 

onBind()

returns (for example, a subclass that implements RPC methods) would be called from threads in the pool. Because a service can have more than one client, more than one pool thread can engage the same 

IBinder

method at the same time. 

IBinder

 methods must, therefore, be implemented to be thread-safe.

Similarly, a content provider can receive data requests that originate in other processes. Although the

ContentResolver

 and 

ContentProvider

 classes hide the details of how the interprocess communication is managed, 

ContentProvider

 methods that respond to those requests—the methods 

query()

insert()

delete()

,

update()

, and 

getType()

—are called from a pool of threads in the content provider's process, not the UI thread for the process. Because these methods might be called from any number of threads at the same time, they too must be implemented to be thread-safe.