File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes local varriable vs instance varriable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "local varriable vs instance varriable" Watch "local varriable vs instance varriable" New topic

local varriable vs instance varriable

sahidul karim

Joined: Sep 19, 2006
Posts: 28
i am creating a dao servlet class .All the database transaction are here.which one in better to use .local varriable or instance varriable ?
with respective to single thread and multithread?
Rahul Bhattacharjee
Ranch Hand

Joined: Nov 29, 2005
Posts: 2308
What is DAO servlet ?

Rahul Bhattacharjee
LinkedIn - Blog
sahidul karim

Joined: Sep 19, 2006
Posts: 28
Database accesing class
pascal betz
Ranch Hand

Joined: Jun 19, 2001
Posts: 547
your DB access code should not go in the Servlet... but that is another story.
Multithreading and instance variables do always offer the possibilities that something goes wrong IF not proper accessed/synchronized. Method local variables on the other hand are on the stack and are not "visble" to other threads.

That said, there are of course variables that need to be instance level and some that need to be method level...

So what variables (references ?) are you talking about ?

sahidul karim

Joined: Sep 19, 2006
Posts: 28
When will i go for instance varriable and when will i go for method varriable? give me some example.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15082

You are talking about a servlet, right?

Never use instance variables in servlets to store state. You do not have control over how many instances of your servlet are created; the servlet container controls this.

If you need to store state that needs to be accessible beyond the method in a web application, you should store it as attributes in the session. For example (untested code, it's been a while since I programmed a servlet):

I don't know what you are planning to store, but note that you cannot store database connections in the session this way. You should use a database connection pool for that, and retrieve a connection from the pool each time you need it (and release it back to the pool once you're done with it).
[ November 17, 2006: Message edited by: Jesper Young ]

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
I agree. Here's the link:
subject: local varriable vs instance varriable
It's not a secret anymore!