Jump to content
Main menu
Main menu
move to sidebar
hide
Navigation
Main page
Recent changes
Random page
Help about MediaWiki
Special pages
Niidae Wiki
Search
Search
Appearance
Create account
Log in
Personal tools
Create account
Log in
Pages for logged out editors
learn more
Contributions
Talk
Editing
Comparison of Java and C++
(section)
Page
Discussion
English
Read
Edit
View history
Tools
Tools
move to sidebar
hide
Actions
Read
Edit
View history
General
What links here
Related changes
Page information
Appearance
move to sidebar
hide
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
=== Resource management === * Java offers automatic [[Garbage collection (computer science)|garbage collection]], which may be bypassed in specific circumstances via the [[Real time Java]] specification. Memory management in C++ is usually done via constructors, destructors, and [[smart pointer]]s. The C++ standard permits garbage collection, but does not require it. Garbage collection is rarely used in practice. * C++ can allocate arbitrary blocks of memory. Java only allocates memory via object instantiation. Arbitrary memory blocks may be allocated in Java as an array of bytes. * Java and C++ use different idioms for resource management. Java relies mainly on garbage collection, which can reclaim memory,{{sfn|Bloch|2018|loc=Chapter §2 Item 8: Avoid finalizers and cleaners|pp=29-33}} while C++ relies mainly on the [[Resource Acquisition Is Initialization]] (RAII) idiom. This is reflected in several differences between the two languages: ** In C++ it is common to allocate objects of compound types as local stack-bound variables which are destroyed when they go out of scope. In Java compound types are always allocated on the heap and collected by the garbage collector (except in virtual machines that use [[escape analysis]] to convert heap allocations to stack allocations). ** C++ has destructors,{{sfn|Bloch|2018|loc=Chapter §2 Item 8: Avoid finalizers and cleaners|pp=29-33}} while Java has [[finalizer]]s.{{sfn|Bloch|2018|loc=Chapter §2 Item 8: Avoid finalizers and cleaners|pp=29-33}} Both are invoked before an object's deallocation, but they differ significantly. A C++ object's destructor must be invoked implicitly (in the case of stack-bound variables) or explicitly to deallocate an object. The destructor executes [[Synchronization|synchronously]] just before the point in a program at which an object is deallocated. Synchronous, coordinated uninitializing and deallocating in C++ thus satisfy the RAII idiom. Destructors in C++ is the normal way of getting back the resources associated with an object, and is a needed counterpart to constructors.{{sfn|Bloch|2018|loc=Chapter §2 Item 8: Avoid finalizers and cleaners|pp=29-33}} In Java, object deallocation is implicitly handled by the garbage collector. A Java object's finalizer is invoked [[Asynchrony (computer programming)|asynchronously]] some time after it has been accessed for the last time and before it is deallocated. Very few objects need finalizers. A finalizer is needed by only objects that must guarantee some cleanup of the object state before deallocating, typically releasing resources external to the JVM.{{sfn|Bloch|2018|loc=Chapter §2 Item 8: Avoid finalizers and cleaners|pp=29-33}} Direct usages of finalizers are usually not advised, as they are unpredictable, usually dangerous, and most of the time unneeded.{{sfn|Bloch|2018|loc=Chapter §2 Item 8: Avoid finalizers and cleaners|pp=29-33}} One has to be cautious not to think of finalizers as C++ destructors.{{sfn|Bloch|2018|loc=Chapter §2 Item 8: Avoid finalizers and cleaners|pp=29-33}} Rather, the try-with-resources or try-finally block achieves a more similar purpose as the destructor.{{sfn|Bloch|2018|loc=Chapter §2 Item 8: Avoid finalizers and cleaners|pp=29-33}} One problem with finalizers or cleaners is that it is not guaranteed that they will run immediately.{{sfn|Bloch|2018|loc=Chapter §2 Item 8: Avoid finalizers and cleaners|pp=29-33}} Hence, a finalizer should never be used for tasks that are time-critical.{{sfn|Bloch|2018|loc=Chapter §2 Item 8: Avoid finalizers and cleaners|pp=29-33}} Additionally, finalizers come with severe performance penalties and significantly increase the time it takes for objects to be deallocated, so their use is discouraged and deprecated in Java 9. ** With RAII in C++, one type of resource is typically wrapped inside a small class that allocates the resource upon construction and releases the resource upon destruction, and provide access to the resource in between those points. Any class that contain only such RAII objects do not need to define a destructor since the destructors of the RAII objects are called automatically as an object of this class is destroyed. In Java, safe synchronous deallocation of resources can be performed deterministically using the try/catch/finally construct. Alternatively, the try-with-resources construct, which was introduced in Java 7, should be used in preference to try-finally construct. {{sfn|Bloch|2018|loc=Chapter §2 Item 9: Prefer try-with-resources to try-finally|pp=34-36}} The try-with-resources construct is more concise and readable.{{sfn|Bloch|2018|loc=Chapter §2 Item 9: Prefer try-with-resources to try-finally|pp=34-36}} It also provide more helpful diagnostic information, since suppressed exception are not discarded, and will be printed in the stack trace with information saying that they were suppressed.{{sfn|Bloch|2018|loc=Chapter §2 Item 9: Prefer try-with-resources to try-finally|pp=34-36}} ** In C++, it is possible to have a [[dangling pointer]], a stale [[Reference (computer science)|reference]] to an object that has already been deallocated. Attempting to use a dangling pointer typically results in program failure. In Java, the garbage collector will not destroy a referenced object. ** In C++, it is possible to have uninitialized primitive objects. Java enforces default initialization. ** In C++, it is possible to have an allocated object to which there is no valid reference. Such an [[unreachable object]] cannot be destroyed (deallocated), and results in a [[memory leak]]. In contrast, in Java an object will not be deallocated by the garbage collector ''until'' it becomes unreachable (by the user program). (''[[Weak reference]]s'' are supported, which work with the Java garbage collector to allow for different ''strengths'' of reachability.) Garbage collection in Java prevents many memory leaks, but leaks are still possible under some circumstances.<ref>{{cite web|url=http://www-128.ibm.com/developerworks/rational/library/05/0816_GuptaPalanki/ |title=Java memory leaks – Catch me if you can |author1=Satish Chandra Gupta |author2=Rajeev Palanki |publisher=IBM DeveloperWorks |date=16 August 2005 |access-date=2015-04-02|archive-url=https://web.archive.org/web/20120722095536/http://www.ibm.com/developerworks/rational/library/05/0816_GuptaPalanki/ |archive-date=2012-07-22}}</ref><ref>[https://web.archive.org/web/20140205030750/http://www.openlogic.com/wazi/bid/188158 How to Fix Memory Leaks in Java] by Veljko Krunic (10 Mar 2009)</ref><ref>[https://stackoverflow.com/questions/6470651/creating-a-memory-leak-with-java Creating a memory leak with Java] on [[stackoverflow]].com</ref> The automatic garbage collector may give the false impression that in Java one does not need to think about memory management.{{sfn|Bloch|2018|loc=Chapter §2 Item 7: Eliminate obsolete references|pp=123-125}} However this is not quite true.{{sfn|Bloch|2018|loc=Chapter §2 Item 7: Eliminate obsolete references|pp=123-125}} Loosely speaking, this is because a program can have "memory leaks", more formally known as "unintentional object retentions".{{sfn|Bloch|2018|loc=Chapter §2 Item 7: Eliminate obsolete references|pp=123-125}} An example of a memory leak that may occur is for a program that has been written without any logical errors, except that it did not eliminate obsolete references.{{sfn|Bloch|2018|loc=Chapter §2 Item 7: Eliminate obsolete references|pp=123-125}} This results in higher use of garbage collector activity, higher [[memory footprint]].{{sfn|Bloch|2018|loc=Chapter §2 Item 7: Eliminate obsolete references|pp=123-125}} In extreme circumstances, this problem can lead to an <code>OutOfMemoryError</code>, but this rarely happens. {{sfn|Bloch|2018|loc=Chapter §2 Item 7: Eliminate obsolete references|pp=123-125}} The solution to this is to null out object references. {{sfn|Bloch|2018|loc=Chapter §2 Item 7: Eliminate obsolete references|pp=123-125}} A second common reason for memory leak is the use of cache that has become no longer relevant. The solution to memory leaks due to using old cache is to represent the cache using a <code>WeakHashMap</code>.
Summary:
Please note that all contributions to Niidae Wiki may be edited, altered, or removed by other contributors. If you do not want your writing to be edited mercilessly, then do not submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource (see
Encyclopedia:Copyrights
for details).
Do not submit copyrighted work without permission!
Cancel
Editing help
(opens in new window)
Search
Search
Editing
Comparison of Java and C++
(section)
Add topic