maximus335
maximus335

Reputation: 684

How does Thread.currentThread() work?

Thread.currentThread() is a static method which provides reference to currently executing Thread (basically a reference to 'this' thread).

Accessing non-static members (especially this) inside a static method is not possible in Java, so currentThread() is a native method.

How does currentThread() method work behind the scenes?

Upvotes: 18

Views: 15842

Answers (1)

Marko Topolnik
Marko Topolnik

Reputation: 200148

(basically a reference to 'this' thread)

There are no this references involved here.

You are mixing up a thread as a native resource, meaning the thread of execution; and Thread, which is a Java class. Thread code does not run "within" the Thread instance, that instance is just your handle into Java's thread control. Much like a File instance is not a file.

So, Thread.currentThread() is a way for you to retrieve the instance of Thread in charge of the thread-of-execution inside which the method is called. How exactly Java does this is an implementation detail which should not be your concern unless you are exploring the details of a particular JVM implementation.

Upvotes: 12

Related Questions