0

While I was going through the source code of andorid.os.HandlerThread class, I found that Process.myTid() was being used as Thread ID.

I searched it a bit and found this helpful answer, now I understand what is myTid and what's the difference between myTid & Thread.getId().

Here is my question;

WHY we need to get the ID from Process.myTid()? Why not use Thread.getId()?

@Override
public void run() {
    mTid = Process.myTid();
    Looper.prepare();
    synchronized (this) {
        mLooper = Looper.myLooper();
        notifyAll();
    }
    Process.setThreadPriority(mPriority);
    onLooperPrepared();
    Looper.loop();
    mTid = -1;
}
Community
  • 1
  • 1
mallaudin
  • 4,744
  • 3
  • 36
  • 68

1 Answers1

0

All your Thread runs in a single Process (your application may have more than 1 process). Every single threads runs inside default pool. It means if you create a custom ThreadPools your thread ids may be same but they belongs to different pools but as every threads runs inside a Process so each thread will have its own unique id.

Thread.getId() is simply java static auto-increment long for each thread, (this thread ID may be reused).

Process.getTid() retunrs Os.gettid().

Haris Qurashi
  • 2,104
  • 1
  • 13
  • 28
  • If there are two processes and `Process.getTid()` returns unique ID with in a process. Isn't there any **possibility** of matching IDs? Why do I need to care about matching thread IDs in **two different processes**? What I think is, threads in each process run in isolation from other processes. If we need to share data between processes, we use some protocol but *caring about threads in another process doesn't make sense at all*. Correct me if I am wrong. – mallaudin Feb 22 '17 at 04:44
  • You don't need to care about threads in other process, as you said each process run in isolation from other, so you should't be worry about caring the threads of other process\ – Haris Qurashi Feb 22 '17 at 06:53
  • What about the first part? – mallaudin Feb 22 '17 at 06:54
  • Have a look at [Os.gettid()](https://developer.android.com/reference/android/system/Os.html#gettid()) or Process.getTid() – Haris Qurashi Feb 23 '17 at 08:25
  • I have seen that. It only guarantees uniqueness with in a process. – mallaudin Feb 23 '17 at 08:27