Skip to content

Commit

Permalink
perf: 优化主线程判断代码
Browse files Browse the repository at this point in the history
提高判断是否是主线程的执行效率,自测效益大约是每次执行减少20ms

Looper.myLooper()依赖ThreadLocal进而也依赖Thread.currentThread()。
  • Loading branch information
TestPlanB authored and shifujun committed Dec 30, 2021
1 parent 3d8a6d9 commit 7b366f5
Show file tree
Hide file tree
Showing 4 changed files with 4 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,6 @@ abstract class ShadowPluginLoader(hostAppContext: Context) : DelegateProvider, D
}

private fun isUiThread(): Boolean {
return Looper.myLooper() == Looper.getMainLooper()
return Thread.currentThread() === Looper.getMainLooper().thread
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ class PluginServiceManager(mPluginLoader: ShadowPluginLoader, mHostContext: Cont
private val mainThreadHandler = Handler(Looper.getMainLooper())

private fun <T> execInMainThread(action: () -> T): T {
if (Looper.myLooper() == Looper.getMainLooper()) {
if (Thread.currentThread() === Looper.getMainLooper().thread) {
return action()
} else {
val countDownLatch = CountDownLatch(1)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ internal class DynamicPluginLoader(hostContext: Context, uuid: String) {

private fun isUiThread(): Boolean {

return Looper.myLooper() == Looper.getMainLooper()
return Thread.currentThread() === Looper.getMainLooper().thread
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ public void onServiceDisconnected(ComponentName name) {
}

public final void waitServiceConnected(int timeout, TimeUnit timeUnit) throws TimeoutException {
if (Looper.myLooper() == Looper.getMainLooper()) {
if (Thread.currentThread() == Looper.getMainLooper().getThread()) {
throw new RuntimeException("waitServiceConnected 不能在主线程中调用");
}
try {
Expand Down

0 comments on commit 7b366f5

Please sign in to comment.