Using the current thread's id
Hi,
I saw in JSP is it easy to get the id of the current thread:
long currentThreadId=Thread.currentThread().getId();
I mention that we don't start new threads in our application.
- Can we rely that this currentThreadId doesn't change over the script's execution lifetime?
- Can we rely that nobody else gets the same currentThreadId before our scripts ends?
- Is it safe to save some request specific data in a static HashMap member of a RequestCache class using this currentThreadId as a key?
Thanks!
[554 byte] By [
IMIAa] at [2007-11-27 11:56:06]

... and the javadoc for getId answers you question:
public long getId()
Returns the identifier of this Thread. The thread ID is a positive long number generated when this thread was created. The thread ID is unique and remains unchanged during its lifetime. When a thread is terminated, this thread ID may be reused.
Kaj
kajbja at 2007-7-29 19:05:42 >

Thanks for the ThreadLocal it helps me a lot.
I've read the doc about the getId().
The question is however if somebody can be sure that each request to a script is entirelly executed in one and only one thread...
IMIAa at 2007-7-29 19:05:43 >

> Thanks for the ThreadLocal it helps me a lot.
> I've read the doc about the getId().
>
> The question is however if somebody can be sure that
> each request to a script is entirelly executed in one
> and only one thread...
You do know that JSP isn't script? What do you mean when you talk about script?
kajbja at 2007-7-29 19:05:43 >

You're right, thanks for correcting me, it's easy to guess the PHP background.
I mean a jsp page or a servlet. We're using Tomcat v5.5 currently.
IMIAa at 2007-7-29 19:05:43 >

> You're right, thanks for correcting me, it's easy to
> guess the PHP background.
>
> I mean a jsp page or a servlet. We're using Tomcat
> v5.5 currently.
I haven't written anything in JSP during the last years, and I tend to forget things, but yes I think that one request will be executed by one thread (unless you create other threads).
But as I said, I'm not sure, so I would google on it.
Kaj
kajbja at 2007-7-29 19:05:43 >

Guys,
Yup, each request is definitely executed on one thread, but (if I recall correctly) it's upto the app-server implementation whether it executes a session per thread, a servlet per thread, a servlet request per thread, or get's more creative to handle load-balancing or the like... so regardless of whether it works or not in your current environment I wouldn't rely on it (unless I had no alternative).
I really think you need to check the Tomcat doco (and forums), and read the J2EE specification on threading.
Keith.