Equivalent of Java's Thread.currentThread() in go routine

In Java the thread executing the code can access current thread object using a static method Thread.currentThread(). This object has id, name etc.

Is there an equivalent construct that can be used from within a goroutine?

No. It is technically possible to access it with assembly language or cgo, but you should not; it’s considered bad design in Go. For example, see the documentation to this package that can do it for you:

package id gives you access to the goroutine id. If you use this package, you will go straight to hell.

Whatever you’re trying to do with a goroutine ID should be done some other way. Some common scenarios are:

  1. Logging: Generate your own *Request or requestID and pass it around explicitly or in a context.Context and pass that Context around explicitly. Don’t use the goroutine ID.

  2. “goroutine local storage” (as opposed to thread local storage in other languages). Again, you should either pass cached data around explicitly (or via a Context) or maybe use a sync.Pool, etc. Do not hack together something that uses the goroutine ID.

3 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.