Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare thread objects

I recently came across the sources of AWT's EventQueue where I saw this piece of code:

final boolean isDispatchThreadImpl() {
    EventQueue eq = this;
    pushPopLock.lock();
    try {
        EventQueue next = eq.nextQueue;
        while (next != null) {
            eq = next;
            next = eq.nextQueue;
        }
        if (eq.fwDispatcher != null) {
            return eq.fwDispatcher.isDispatchThread();
        }
        return (Thread.currentThread() == eq.dispatchThread);
    } finally {
        pushPopLock.unlock();
    }
}

What really struggles me is that the thread objects are being compared using ==. So far I've been doing this with equals(Object). I already had a look at this question but the two answers aren't really what I'm looking for.

Is it possible that two different instances refer to the same native thread? How should I compare thread objects for equality?

like image 809
beatngu13 Avatar asked Dec 14 '22 03:12

beatngu13


1 Answers

Is it possible that two different instances refer to the same native thread?

No.

According to the Thread javadoc:

A thread is a thread of execution in a program.

The life cycle of a Thread object has three phases:

  • Prior to the start() call, a Thread object denotes a thread that has yet to be created. And might never be created; i.e. if start() isn't called. (At this point, there is no native thread.)

  • After the start() call, and until the run() call terminates, the Thread object denotes a live thread. (At this point, there is a native thread.)

  • After the run() call terminates, the Thread object denotes a thread that no longer exists. (At this point the native thread that embodied the thread has been deleted.)

At no point does it make any sense for two distinct Thread objects to denote the same thread; i.e. the same thread of execution.

How should I compare thread objects for equality?

Using == is the right way.

But equals(Object) is also correct, because Thread inherits it from Object where it is defined to be the same as ==.


On the point of style.

Some would argue that is is stylistically better to use equals. However, in this context, the Thread javadoc (in effect) specifies that equals and == do the same thing. Indeed, reference equality is the only equality semantics that would make any sense for Thread objects. This follows from the way that the `Thread life-cycle works, and the fact two distinct threads of execution intuitively. (They could consistently produce the same results, but that is "emergent" behavior ... and proving that behavior is in general an intractable problem.)

On the other hand, this question wasn't about style. It was about whether == is semantically correct in this context. And it is.

like image 122
Stephen C Avatar answered Dec 27 '22 05:12

Stephen C