ThreadLocal and the API doc

Hi,
I'm trying to understand ThreadLocal. The API javadoc provides the following example of a use of a ThreadLocal at http://java.sun.com/javase/6/docs/api/ :
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();
} // UniqueThreadIdGeneratorHowever I'm not sure I get this right. As far as I can tell, uniqueId is not thread-local, and will return basically the number of threads (minus 1) that have been created at any point in time, for any thread (rather than a unique ID for each thread). Shouldn't it be
public static int getCurrentThreadId() {
         return uniqueNum .get();
     }(ie uniqueNum rather than uniqueID)? I can't imagine this error not having been spotted earlier, but I've looked online and can't find anything about it. Is there some understanding I'm missing?
Thanks,
Lis

Ok I'm not a big thread pro (if that wasn't clear already ; ) ), so I tested this best I could. I copied the test class of the API and renamed to ThreadLocalTest. I then ran the following main:
public class ThreadLocalTestrun
     public static void main(String[] args)
          System.out.println("at the start - " + ThreadLocalTest.getCurrentThreadId() + " - " + Thread.currentThread().getName());
          new MyThread("NewThread-1").start();
          new MyThread("NewThread-2").start();
          System.out.println("in the end - " + ThreadLocalTest.getCurrentThreadId() + " - " + Thread.currentThread().getName());
     public static class MyThread
          extends Thread
          String message;
          MyThread(String name)
               super(name);
          @Override
          public void run()
               boolean hasRun = false;
               while (!hasRun)
                    System.out.println("Current Thread Id: " + ThreadLocalTest.getCurrentThreadId() + " (name '" + Thread.currentThread().getName() + "')");
                    hasRun = true;
}If I run the code with the uniqueId call, I get the following output:
at the start - 0 - main
in the end - 0 - main
Current Thread Id: 0 (name 'NewThread-1')
Current Thread Id: 0 (name 'NewThread-2')(and I don't understand why uniqueId hasn't been incremented except perhaps that uniqueNum never gets instantiated because it's not called?)
I then ran it with uniqueNum instead and got this:
at the start - 0 - main
in the end - 0 - main
Current Thread Id: 2 (name 'NewThread-1')
Current Thread Id: 1 (name 'NewThread-2')which looks a lot more like assigning a unique Id to a thread.
Is there something more subtle at play here which I'm not getting? Why would the int returned by uniqueId be thread-local, if uniqueId itself isn't?

Similar Messages

  • Classes are missing in the api doc's

    Some of the class that my java book says are available aren't documented on th web. Am I missing something, or is the api doc behind the times?

    Here is the result of pervel's manual API search service: http://java.sun.com/j2se/1.4.1/docs/api/java/awt/Graphics.html
    Do you need any other searches done?

  • Where can i download the api doc ?

    I'm writting Extension tool for jdeveloper
    In the development, i need to use many class from oracle.ide.* packages.
    But i cant find the api doc in oracle.com
    Dose anyone know where i can see them ?

    The extension API javadoc is included in the Online help in JDeveloper, or you can extract it from ${jdev.home}/jdev/doc/ohj/jdev-doc.jar.
    Thanks,
    Brian ([email protected])
    JDev Team

  • Where are the API Docs of the appserv-rt.jar classes and others?

    Where do I find the API Documentation/Specification for the classes of :
    com.iplanet ...
    com.sun.appserv ...
    com.sun.enterprise.security ...
    The very of appserv-rt.jar and appserv-rt-ee.jar
    I need it for AS7 (J2EE 1.3) and AS8 (J2EE 1.4).
    Something like http://java.sun.com/j2ee/sdk_1.3/techdocs/api/index.html would be nice

    For AS8, the docs subdirectory under your installation directory will have javadocs for all classes in com.sun.appserv and javax... namespace.
    For AS7, what is it that you are specifically looking for?
    In general, com.sun.enterprise... classes are not documented. There are exceptions and you should be able to find them in developer's guide.
    Finally, you might want to look at the source code in the Open Source Application Server project GlassFish (http://glassfish.dev.java.net).

  • Javafx.scene.layout.Priority missing from the API Doc

    I notice there is an important class "javafx.scene.layout.Priority" missing from the JavaFX 1.3 API Doc. I can still use that class without any problems in my apps.

    Thanks for spotting that - I'll fix that before the next release.

  • Named Anchors and the HTML doc

    Normally, when using the the default "Flash Only" setting in the HTML publish settings, you can set the dimensions to 100 x 100 percent.  This will make the Flash movie fill the browser window and resize with the browser.
    I'm using named anchors and am using the "Flash with Named Anchors" setting in the HTML publish settings.  Everything else is the same as when I use the "Flash Only" template.  However, when I publish this HTML document it is not filling the browser window correctly.  Instead, the movie is being displayed as if I had set the movie size to 100 x 100 pixels instead of percent.  In other words, the Flash movie is squeezed into a size of 100 x 100 pixels.  Something is causing it to misinterpret percent as pixels.
    I've looked at the HTML document and it correctly says width="100%" height="100%".  This problem occurs in Firefox 3.6.  Everything displays correctly in IE8 and Safari 5.  Thank you in advance to anybody with advice or a solution.

    helpall wrote:
    > I looked in my books and help but found nothing on
    linking to anchors in Spry
    > panels. I have this sinking feeling that DW doesn't let
    you link to anchors in
    > specific panels. Or am I wrong and just need to add
    additional code to the link
    > besides the url and the #anchor name?
    It has nothing to do with what Dreamweaver will let you do
    nor not do, it has to do with what you the panels are "told" to do
    in certain situations. In this case you want to open a specific
    panel, preferably based upon the anchor name that you're already
    using. Take a look at the URL Utilities sample page, in particular
    at the last example:
    http://labs.adobe.com/technologies/spry/samples/utils/URLUtilsSample.html
    This means you'd need to get the full Spry download:
    http://labs.adobe.com/technologies/spry/home.html
    If you wanted, you could add a query string parameter like
    the above example does, but that might mean changing a lot of
    links.
    Or you could modify the example code above to "slice" out the
    first letter of the anchor and figure out the index of the tab to
    show (they use a 0 based index, so 'a' would 0 and 'z' would be 25.
    Try the following:
    <script type="text/javascript">
    <!--
    var hash = window.location.hash;
    if(hash){
    // get the character code of the upper case of the first
    letter then subtract 65
    // 'A' has a character code of 65, so the subtraction gets
    our tab index from 0 to 25
    var charCode = hash.toUpperCase().charCodeAt(0)-65;
    if(charCode < 0 || charCode > 25){ // If not in A-Z
    range, use default for 'a'
    charCode = 0;
    else{
    // Default to tab 0, or 'a' when no hash present
    var charCode = 0;
    //The defaultTab value checks to see if the url param is
    defined. If it is not, it sets it to 0.
    var
    var TabbedPanels1 = new
    Spry.Widget.TabbedPanels("TabbedPanels1", {defaultTab: charCode });
    //-->
    </script>
    Danilo Celic
    |
    http://blog.extensioneering.com/
    | WebAssist Extensioneer
    | Adobe Community Expert

  • Where's the API docs for J2ME?

    I'm a long time J2SE programmer wanting to get into J2ME> One of the first things I tried to do is find Sun's javadoc for J2ME, but I can't find it anywhere. How can I find them? Also, are there any good learning trails for learning the basics of the J2ME windowing system and such?

    http://java.sun.com/j2me/docs/index.html
    or you can search in
    http://jcp.org/en/home/index
    by JSR
    http://java.sun.com/j2me/index.jsp

  • Coldfusion, JSON, and the Amazon CloudSearch API

    Hi all,
    We are using Amazon CloudSearch service for our site search.  We created a front end which uses jquery to communicate with the server to display search results.
    The problem we are running into is with creating and updating data on the backend.  We have been creating new domains and uploading whole data sets manually from spreadsheets which is obviously not going to work for us long term.
    The cloud search uses has an API that we can send JSON to for updating the items.  I have created the nested json like this (the query name and data has been changed to protect the innocent):
    <cfscript>
      variables.dataFields = {};
              variables.dataFields['id'] = " #getsdata.id#";
              variables.dataFields['lang'] = "en";
              variables.dataFields['type'] = "add";
              variables.dataFields['version'] = " #DateFormat(Now(),"YYMMDD")##TimeFormat(Now(),"HHMM")#";
      variables.dataFields['fields'] = {};   
      variables.dataFields.fields['redfield'] = "#getsdata.redfield#";
              variables.dataFields.fields['blackfield'] = "#getdata.blackfield#";
      variables.dataFields.fields['purplefield'] = "#getdata.purplefield#";
    variables.dataFields = serializejson(variables.dataFields);
    </cfscript>
    When I dump that json out, it looks pretty good (there are many more fields).  For now, I added a space before numbers to work around a bug I read about in the serializedjson function in CF8 that sees all numbers as numbers even if they are expressed as strings.  I will figure that out later.
    The code to post the json is:
    <cfhttp url="http://doc-ourcompanydomain-abunchofnumbers.us-west-2.cloudsearch.amazonaws.com/2011-02-01 /documents/batch" method="post"  result="httpResp">
      <cfhttpparam type="header" name="Content-Type" value="application/json"  />
      <cfhttpparam type="header" name="Accept" value="application/json" /> 
      <cfhttpparam type="header" name="Content-Length" value="#Len(variables.dataFields)#" />
      <cfhttpparam type="body" value="#variables.dataFields#" />
      </cfhttp>
    The response I get is "400 Bad Request"
    I know that there aren't that many people using cloud search and Coldfusion but I was hoping somebody might see a noob mistake in my code or methods.
    Thanks!
    Red

    Hi Peter,
    Thank you for your response.  For some reason, I was not able to reply to my own post.  Maybe I just wasn't signed in.
    Anyway, the problem was with the json that I was uploading and not with my method for uploading it.  I was actually able to remove the "Accept" and "Content-Length" params.
    I had added a space in front of the ID so that the serializedjson function would treat it as a string and not a number but the API required that field start with an alphanumeric character.  Since I am using the sku number for that product, I just changed it to sku12345 etc so that it was seen by the serializedjson function as a string and the API would accept it.
    Also, I had to add brackets around the enitre body because the Cloudsearch API wanted the entry to be an array so I just added:
    <cfset theuploaddata = "[" & variables.dataFields & "]">
    Once I made those changes, the server responded with a 200 code and updated the item.  Now I just need to figure out how to get arrays past the CF json tag.  Some of our json is set up for the cloudsearch in arrays like colors.  The facets need to appear in the upload as "Colors" : ["Red","Blue"] but the serialized json tag automatically escapes the quotes in the facets.  I think I saw some third party custom tags that I can use as a work around. 
    Thanks again for your help.  The Cloudsearch service has been awesome so far.  We are really happy with it.  We are a small to midsized company and the cost of a dedicated search company was 10-15 as much as the cloud search and they basically wanted total control of the site.  The cloudsearch required a considerable amount of work to set up but it works beautifully.  Since we use it for navigation too, I have been thinking about caching the json for the common requests.
    Red

  • Create symbol and animate (example from API doc working?)

    Might be missing something simple, but this doesn't seem to work and it is right out of the API doc
    brand new edge animate file.
    make a rectangle - convert to symbol with name "kitten_paw"
    delete from stage
    paste this code in time line (say at 1000)
    sym.createChildSymbol("kitten_paw", "Stage");
    var kitten_sym = kitten_paw.getSymbolElement();
    kitten_sym.animate({opacity: 0}, 500);
    it creates the object but doesn't animate it - and console returns an error - edge.2.0.1.min.js:162Javascript error in event handler! Event Type = timeline
    Am I missing something?
    thanks!

    Try this:
    var kitten_paw = sym.createChildSymbol("kitten_paw", "Stage");
    var kitten_sym = kitten_paw.getSymbolElement();
    kitten_sym.animate({opacity: 0}, 500);

  • Someone rewrite the JMF API docs!

    Anyone know if the data that comes out of an audio CaptureDevice is framed? Can it lose data (ie does it have a limited capture buffer?)
    This really should have a device independent front end.
    JMF is really, really bad. Unless you want to do absolutely nothing complicated or original. There's more to multimedia than streaming sound and video to or from a device. JMF is impossible to synchronise, or even get synchronised with. It does not define well the data it handles, and doesn't even interface well with the rest of Java!
    This forum seems as useless as t*ts on a bull, unless you want to play and MPG from disk, which sux because the API docs for JMF leave out alot of information.

    In case anyone here actually cares, I've given up. C++ here I come. Now it will take twice as long to develop but at least it will have some balls!

  • How to see the source code in the API?

    Is it possible to see the source code for the String class in the Java API 1.4.2 somehow?

    one of the IDE's I have is GEL (gexperts.com), all you do is
    Search/Go To Class/
    select the class String, and the source code is displayed.
    pre-requisite is you have to specify the location of the api docs on your pc when
    installing GEL

  • Downloading SE 6 API Doc

    Is it possible to download the entire Java™ Platform, Standard Edition 6 API Specification documentation?
    I once downloaded the SE 5 API doc and it is a big help to be able to use it when on-line access is not possible (i.e. - on an airplane).
    Thanx,
    Ron

    r035198x wrote:
    You probably could also generate from the src.zip that came with the JDK.Only as a last resort. It's much more complicated than you might expect, and it takes quite a while--much longer than a broadband download. Besides, there's a lot more in the download than just the API docs.

  • How to read the API

    I am trying to understand how to read the Java API. I have bought Oracle's Books "Java The Complete Reference" and "Java A Beginners Guide" but am still unsure how to read the API.
    Let me clarify what I'm asking to avoid confusion.
    The class java.util.ProcessBuilder http://download.oracle.com/javase/7/docs/api/
    Has a Constructor section that lists
    Constructor and Description
    ProcessBuilder(List<String> command)
    Constructs a process builder with the specified operating system program and arguments.
    ProcessBuilder(String... command)
    Constructs a process builder with the specified operating system program and arguments.
    How do I read the ProcessBuilder(List<String> command) so that I can understand it and implement its use?
    Later when it talks about methods such as List<String>      command()
    Returns this process builder's operating system program and arguments.
    How do I understand this and make use of the method?
    Is it possible for this to be explained to cover the whole API so that when a class is looked up the constructor and methods are explained that someone who does not understand can take any class and have the constructor and methods from the API and know how to implement them?
    Thank you
    FtroopSon

    FtroopSon wrote:
    My Instructor said we can not work with others on our project, so instead of violating that rule, I asked something about JAVA here. My question was general enough to not violate the instructors rule, but specific enough to learn what I felt I was missing.I hope you don't think I was suggesting you're doing anything wrong - far from it - I was simply saying that ProcessBuilder isn't the first class I would choose if I was trying to get familiar with the Java API pages.
    As with a lot of questions like this, Google is your friend. A Google of "using ProcessBuilder" gave me a pile of useful pages on how to use the class (which the API docs aren't always wonderful at doing), including some common 'gotchas' - although many of these are related to <tt>Runtime.exec()</tt>, which Process/ProcessBuilder was created to improve.
    One of those pages was for [url http://commons.apache.org/exec/index.html]Apache Commons Exec, which you might also want to look at (although it does require a download, and that might violate the rules of your exercise too). I've never used it myself though, so I can't comment on how good it is.
    Alternatively, it might be worth talking to your instructor and explaining your problem. Most of us are reasonable chaps, and s/he might be able to provide you with some good tips.
    Remember: plagiarism is the programmer's stock-in-trade. There's nothing wrong with using something written by someone else as long as you attribute it - that is, after all, what classes are all about :-).
    Winston

  • Where is the api documentation?

    Um, I signed up for my key and cannot find the api docs anywhere.
    Would someone please provide a link to the api documentation?
    Thank you.

    Wait... is this it? https://learn.adobe.com/wiki/display/kulerdev/B.+Feeds
    Oh lord...

  • API docs in JavaHelp format?

    The API docs are available in WinHelp and HTMLHelp formats. I was just wondering, has anyone heard of the API docs being provided in the JavaHelp format? If so, could you please provide relevant links?
    Thanks!

    Google has approximately one reference to a doclet which output in JavaHelp format. It doesn't appear to be available elsewhere. However, if you have to produce your own solution a doclet is probably the way forward.

Maybe you are looking for