tags:

views:

195

answers:

1

Consider an case that I have to call C++ code from my Java Program. The C++ code creates thousands of Objects. Where are these dynamic objects stored ? I suspect in the JVM heap because the native code will be a part of the same process as the JVM.

If yes, do the rules of Java Garbage collector thread apply on Objects of the C++ code ?

+3  A: 

For the first question, C++ will allocate resources using its own runtime which has nothing to do with the JVM - the JVM is not aware of any activity in this memory allocator.

For the second question, the Java garbage collector will not GC the memory allocated by C++. You will have to make sure that your Java wrapper initiates the memory release. Before an object is GC'd by java, the runtime calls the finalize() method. The default one is inherited from java.lang.Object and basically does nothing. You can override this and use it as a hook to initiate deallocating your manually managed memory.

ConcernedOfTunbridgeWells
@Geek - yes. It's all part of the same process, so a crash in your C++ will take down the JVM
Brian Agnew
Yes, it runs in the same process as the JVM and most certainly can crash the process.
ConcernedOfTunbridgeWells
Thanks Brian and CTW. I don't understand. How is it possible to have One Process and have memory allocation different for C++ and Java. Is Heap Memory not a part of the Address space of a Process. I think only the objects on Stack are a part of the address space. Please comment.
Geek
Heap memory is certainly within the address space of the process. Behind the scenes, both the JVM and C++ runtime request chunks of memory from the O/S using system calls such as sbrk(). As long as they stay within the bounds of the chunks that they request they won't trip over each other.
ConcernedOfTunbridgeWells
Thanks CTW, your answers were very informative. Where can I read more about it.
Geek
Depending on what platform you are using a good system internals book such as Stevens' 'Advanced Programming in the Unix Environment' for Unix or Petzold or Richter for Windows should give you a good feel for the system level machinations. There are quite a few JVM internals books in print, but unfortunately I haven't read any of them. Googling for jvm, garbage collecting, finalize(), jni (Java Native Interface) and other related keywords should give you plenty of web resources on the subject.
ConcernedOfTunbridgeWells