• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How Memory is Allocated in Java when Instantiating an Object

 
K Nally
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi:
I have a basic question on when memory is allocated for an object and if that memory is "shared" between the class that instantiates it and the class itself. I am using "class" and "objects" interchangeably here.
In the following example, do we have one memory allocation of Statement st or two memory allocations (myServlet's and DBConnect)?
myServlet:
DBConnection dbconnect = new DBConnection();
Statement st = dbconnect.setConnection();
Java Class:
public class DBConnect implements Serializable {
private Connection conn = null;
private Statement st = null;
public DBConnection() {
}
public Statement setConnection() {
<other statements>
conn = ds.getConnection(...);
st = conn.createStatement();
return st;
}
}

Thanks!
[ January 30, 2004: Message edited by: K Nally ]
[ January 30, 2004: Message edited by: K Nally ]
[ January 30, 2004: Message edited by: K Nally ]
 
Ken Krebs
Ranch Hand
Posts: 451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Both references to the Statement object point to the same area of memory which is on the heap.
The memory for the "st" reference in DBConnect is allocated on the heap and is private to the DBConnect instance.
If myServlet is a "good little servlet", i.e. threadsafe, the memory for the "st" reference in DBConnect is local to the method and allocated on the stack.
If myServlet is NOT a "good little servlet", the memory for the "st" reference in DBConnect is an instance variable and is allocated on the heap.
 
Greg Reinl
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ken Krebs wrote:
If myServlet is a "good little servlet", i.e. threadsafe, the memory for the "st" reference in DBConnect is local to the method and allocated on the stack.
If myServlet is NOT a "good little servlet", the memory for the "st" reference in DBConnect is an instance variable and is allocated on the heap.

Did you mean to say that the memory for the "st" reference in the servlet is local (for the good little servlet) or an instance variable (for the bad little servlet)? If not, then I'm confused about soemthing that I thought I was just starting to understand.
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13055
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Memory for actual objects is always on the heap. Calls to methods create space to store the references to objects or actual primitive values on the stack. Just keep making the distinction between the memory the object lives in and the memory the reference variable lives in and you will be ok.
Bill
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic