Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 875371
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T11:15:30+00:00 2026-05-15T11:15:30+00:00

I’ve been reading about ThreadLocal, trying to understand how it works and why we

  • 0

I’ve been reading about ThreadLocal, trying to understand how it works and why we need it.

So far what I’ve been able to learn is the following:

  1. ThreadLocal class allows to hold 1 instance of an object at the thread level
  2. The instance is created by overriding initialValue()
  3. The instance is actually stored in the each thread’s HashMap
  4. A common sense usage example can be found here

All seemed fine, until I tried to run the example from the javadoc, the code is provided as following:

 import java.util.concurrent.atomic.AtomicInteger;

 public class UniqueThreadIdGenerator {

     private static final AtomicInteger uniqueId = new AtomicInteger(0);

     private static final ThreadLocal < Integer > uniqueNum = 
         new ThreadLocal < Integer > () {
             @Override protected Integer initialValue() {
                 return uniqueId.getAndIncrement();
         }
     };

     public static int getCurrentThreadId() {
         return uniqueId.get();
     }
 } // UniqueThreadIdGenerator

If I understand this code correctly, calling getCurrentThreadId() should return the correct auto incremented thread number, alas it returns 0 for me. ALWAYS 0, without consideration of how many threads I have started.

To get this working for me I had to change getCurrentThreadId() to read

     public static int getCurrentThreadId() {
         return uniqueId.get();
     } 

In which case I am getting correct values.

My code is provided below, what am I missing? (It’s not that the javadoc is actually wrong, right??)

package org.vekslers;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class UniqueThreadIdGenerator extends Thread {

    private static final AtomicInteger uniqueId = new AtomicInteger(0);

    private static final ThreadLocal <Integer> uniqueNum = 
        new ThreadLocal <Integer> () {
            @Override protected Integer initialValue() {
                return uniqueId.getAndIncrement();
        }
    };

    public static int getCurrentThreadId() {
        return uniqueNum.get();
    }




    //////////////////////////////////////////////////
    // Testing code...
    //////////////////////////////////////////////////
    private static volatile boolean halt = false;

    public UniqueThreadIdGenerator(String threadName) {
        super(threadName);
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread() + " PREHALT " + getCurrentThreadId());
        while(!halt)
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
            }
        System.out.println(Thread.currentThread() + " POSTHALT " + getCurrentThreadId());
    }

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new UniqueThreadIdGenerator("t1");
        Thread t2 = new UniqueThreadIdGenerator("t2");
        Thread t3 = new UniqueThreadIdGenerator("t3");
        Thread t4 = new UniqueThreadIdGenerator("t4");

        t3.start();
        t1.start();
        t2.start();
        t4.start();

        TimeUnit.SECONDS.sleep(10);
        halt = true;
    }
} // UniqueThreadIdGenerator

Output:

Thread[t3,5,main] PREHALT 0
Thread[t1,5,main] PREHALT 1
Thread[t2,5,main] PREHALT 2
Thread[t4,5,main] PREHALT 3
Thread[t4,5,main] POSTHALT 3
Thread[t2,5,main] POSTHALT 2
Thread[t1,5,main] POSTHALT 1
Thread[t3,5,main] POSTHALT 0

p.s. Code comments OT or to the point are welcome in comments.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T11:15:30+00:00Added an answer on May 15, 2026 at 11:15 am

    The javadocs are wrong.
    https://bugs.java.com/bugdatabase/view_bug?bug_id=6475885

    Java 7’s javadoc includes

     import java.util.concurrent.atomic.AtomicInteger;
    
     public class ThreadId {
         // Atomic integer containing the next thread ID to be assigned
         private static final AtomicInteger nextId = new AtomicInteger(0);
    
         // Thread local variable containing each thread's ID
         private static final ThreadLocal<Integer> threadId =
             new ThreadLocal<Integer>() {
                 @Override protected Integer initialValue() {
                     return nextId.getAndIncrement();
             }
         };
    
         // Returns the current thread's unique ID, assigning it if necessary
         public static int get() {
             return threadId.get();
         }
     }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to understand how to use SyndicationItem to display feed which is
I am reading a book about Javascript and jQuery and using one of the
I have a jquery bug and I've been looking for hours now, I can't
link Im having trouble converting the html entites into html characters, (&# 8217;) i
Basically, what I'm trying to create is a page of div tags, each has
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am doing a simple coin flipping experiment for class that involves flipping a
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and
In my XML file chapters tag has more chapter tag.i need to display chapters
I am trying to render a haml file in a javascript response like so:

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.