Win a copy of Java Concurrency Live Lessons this week in the Threads forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

thread safe variables  RSS feed

 
felix thomas
Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

hi,

I have a question suppose in the below eg

<%!
int i=10;
public String str()
{
int t= 15 ;
return "test";
}
%>

are both variables i and t thread safe or is only t thread safe.
 
Paul Frey
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The variable t would be threadsafe but the variable i would be defined as a page variable and therefore would exist at the class level and is therefore, not threadsafe.
 
Mary O'yang
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How come? Paul, do you mind giving me more explaination on your answer? Does page's isThreadSafe attribute have anything to do with those variables?

Thanks a lot.
Mary.
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 65833
134
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For the same reason that instance variables are unsafe in servlets.

The container will generate a servlet on behalf of the JSP and will create one instance of the servlet that will serve any threads created to respond to requests for that page. So if the page is requested simultaneously, there will be contention for the single instance of the instance variable.

This is one of the very many many many reasons that current conventional wisdom dictates that this type of Java processing in JSPs is a very poor practice. Leave the Java in the servlets and use JSPs for renderring the view as nature intended,
 
Ben Souther
Sheriff
Posts: 13411
Firefox Browser Redhat VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Mary O'yang:
How come? Paul, do you mind giving me more explaination on your answer? Does page's isThreadSafe attribute have anything to do with those variables?
Thanks a lot.
Mary.


Mary,
The isThreadSafe directive does affect these variables. It's usually implemented in the generated servlet code with the "SingleThreadedModel" which has been deprecated. The JSP Spec (JSP.1-8) advises against using this directive.

With servlets that implement SingleThreadedModel the entire servlet needs to be instanciated for each request, as opposed to the 'single servlet spawning a new thread for each request' pattern which is much more efficient.

As Bear stated earlier, it's much better to write your Java code in a thread-safe servlet and use JSP for handling the view.

Although, I'm not sure it has anything to do with nature..
Maybe the nature of the JCP..
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!