File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Servlets and the fly likes int to string conversions threadsafe? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "int to string conversions threadsafe?" Watch "int to string conversions threadsafe?" New topic

int to string conversions threadsafe?

Stephen Peterson
Ranch Hand

Joined: Dec 25, 2000
Posts: 33
If I have a need in a servlet to convert an integer to a string,
I know of these 2 options:
1) String s = Integer.toString(i)
2) String s = (new Integer(i)).toString()
It seems that the 1st method would be more memory-efficient.
But is the 1st method not threadsafe if it is not synchronized,
and thus would I be better off using the 2nd method?
United Health Group
Hartford, CT, USA

United Health Group<BR>Hartford, CT, USA
Phil Hanna
Ranch Hand

Joined: Apr 05, 2001
Posts: 118
Why would you think Integer.toString(i) is not threadsafe? It does not access anything but its own local variables.
Most often, I use String.valueOf(i).
Phil Hanna
Sun Certified Programmer for the Java 2 Platform
Author of :
JSP: The Complete Reference
Instant Java Servlets

Phil Hanna<BR>Sun Certified Programmer for the Java 2 Platform<BR>Author of :<BR><A HREF="" TARGET=_blank rel="nofollow">JSP: The Complete Reference</A><BR><A HREF="" TARGET=_blank rel="nofollow">Instant Java Servlets</A>
Stephen Peterson
Ranch Hand

Joined: Dec 25, 2000
Posts: 33
Hi Phil,
The point I am not clear on, is whether local variables work in static methods the same way they work in non-static methods.
I've read that local variables are created on a stack that is assigned by the JVM to each thread. You seem to be saying that this is true regardless of whether the method is static or non-static. I could not find a statement that explicitly said that in the Java 2.0 language spec document at
But I may not know where to look.
Is there a way I prove to myself that local variables are always threadsafe in a static method? Does the language spec spell this behavior out somewhere?
William Brogden
Author and all-around good cowpoke

Joined: Mar 22, 2000
Posts: 13036
Local variables are always Thread safe because the only reference is in the stack of a single Thread. There is no difference between static and instance methods in the way they are called. Probably the reason you didn't find a statement to that effect is that it never occurred to anybody to doubt it.
When in doubt about any method - look at the source code for the class.
Stephen Peterson
Ranch Hand

Joined: Dec 25, 2000
Posts: 33
thanks Bill. I believe you.
I agree. Here's the link:
subject: int to string conversions threadsafe?
It's not a secret anymore!