{"id":402,"date":"2021-01-04T17:31:44","date_gmt":"2021-01-04T17:31:44","guid":{"rendered":"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/?page_id=402"},"modified":"2021-01-09T22:05:31","modified_gmt":"2021-01-09T22:05:31","slug":"instance-destruction","status":"publish","type":"page","link":"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/course-topics\/classes-objects\/instance-destruction\/","title":{"rendered":"Instance Destruction"},"content":{"rendered":"<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_83 counter-hierarchy ez-toc-counter ez-toc-grey ez-toc-container-direction\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<label for=\"ez-toc-cssicon-toggle-item-6a06ed55affd1\" class=\"ez-toc-cssicon-toggle-label\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #999;color:#999\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #999;color:#999\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/label><input type=\"checkbox\"  id=\"ez-toc-cssicon-toggle-item-6a06ed55affd1\"  aria-label=\"Toggle\" \/><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/course-topics\/classes-objects\/instance-destruction\/#In_C_objects_are_destroyed_using_class_destructors\" >In C++, objects are destroyed using class&nbsp;destructors<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/course-topics\/classes-objects\/instance-destruction\/#In_Java_objects_are_destroyed_automatically_using_a_process_called_garbage_collection\" >In Java, objects are destroyed automatically using a process called&nbsp;garbage collection<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/course-topics\/classes-objects\/instance-destruction\/#In_Java_an_object_becomes_available_for_garbage_collection_when_the_number_of_references_to_that_object_drops_to_zero\" >In Java, an object becomes available for garbage collection when the number of references to that object drops to zero.<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/course-topics\/classes-objects\/instance-destruction\/#Finalizers_and_finally_blocks\" >Finalizers and finally blocks<\/a><\/li><\/ul><\/nav><\/div>\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"In_C_objects_are_destroyed_using_class_destructors\"><\/span>In C++, objects are destroyed using class&nbsp;<em>destructors<\/em><span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<ul class=\"wp-block-list\"><li>If a C++ object has been allocated using the&nbsp;<strong>new&nbsp;<\/strong>operator, it is the programmer&#8217;s responsibility to remember to clean it up, using the&nbsp;<strong>delete&nbsp;<\/strong>operator. (In C++, you can allocate objects on the run-time stack, or in static space, in addition to from the heap.)<\/li><li>Memory allocation is a very error-prone business in C and C++ &#8212; memory leaks are a constant source of problems, and are very hard to find and fix.<\/li><\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"In_Java_objects_are_destroyed_automatically_using_a_process_called_garbage_collection\"><\/span>In Java, objects are destroyed automatically using a process called&nbsp;<em>garbage collection<\/em><span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<ul class=\"wp-block-list\"><li>There is no&nbsp;<strong>delete&nbsp;<\/strong>operator, as in C++.<\/li><li>There is no&nbsp;<strong>free&nbsp;<\/strong>function or method, as in C.<\/li><li>The Java garbage collector runs in a low-priority thread, so garbage collection takes place when nothing else is happening.<\/li><\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"In_Java_an_object_becomes_available_for_garbage_collection_when_the_number_of_references_to_that_object_drops_to_zero\"><\/span>In Java, an object becomes available for garbage collection when the number of references to that object drops to zero.<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>For example:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; title: ; quick-code: false; notranslate\" title=\"\">\n{\n    Car&#x5B;] carArray = new Car&#x5B;10];\n    for (int i = 0; i &lt; 10; i++)\n\tcarArray&#x5B;i] = new Car();\n\n    process(carArray);\n\n    \/\/ Do more stuff\n\n    \/\/ carArray, etc., becomes eligible \n    \/\/ for garbage collection when it goes out of scope\n}\n<\/pre><\/div>\n\n\n<p>Or, you can give the garbage collector a chance to get rid of an instance earlier, if you know you won&#8217;t need the instance again:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; highlight: [9]; title: ; quick-code: false; notranslate\" title=\"\">\n{\n    Car&#x5B;] carArray = new Car&#x5B;10];\n    for (int i = 0; i &lt; 10; i++)\n\tcarArray&#x5B;i] = new Car();\n\n    process(carArray);\n\n    \/\/ Don&#039;t need carArray any more\n    carArray = null;\t\/\/ eligible for garbage \n\t\t\t\/\/ collection here\n\n    \/\/ Do more stuff\n}\n<\/pre><\/div>\n\n\n<p>You can even &#8216;suggest&#8217; that garbage collection be done:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>System.gc();<\/strong><\/pre>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\"><p><strong>Note:<\/strong> &#8216;gc&#8217; is &#8216;garbage collector&#8217;. It&#8217;s very rarely used.<\/p><\/blockquote>\n\n\n\n<p>In Java, unlike in C++, there are&nbsp;<em><strong>no class destructors<\/strong>.&nbsp;<\/em>You don&#8217;t need them in Java, since allocated memory is cleaned up for you by the garbage collector. (There are situations when you can still get memory leaks, but it&#8217;s much less of a problem than in C\/C++, and Java&#8217;s solution is different &#8212; there are no destructors in Java.)<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Finalizers_and_finally_blocks\"><\/span>Finalizers and finally blocks<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>It&#8217;s true that, in Java, you usually don&#8217;t need a class destructor, because allocated memory is automatically de-allocated by the Java garbage collector.&nbsp; However, sometimes you need to free up a different kind of resource &#8212; for example, file descriptors, GUI Windows, database handles, or network sockets, etc.<\/p>\n\n\n\n<p>It is possible to write a&nbsp;<strong>finalize&nbsp;<\/strong>method for the class:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>protected void finalize() throws Throwable\n{ \/* ... *\/ }<\/strong><\/pre>\n\n\n\n<p>which on the surface sounds like a kind of destructor.<\/p>\n\n\n\n<p>In fact, using <em>finalizers<\/em> is usually more grief than it&#8217;s worth.&nbsp; Why?<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>The time of instance garbage collection is not deterministic.<ul><li>It&#8217;s done in a separate, low-priority thread.&nbsp;&nbsp;<\/li><li>In fact, depending on the program and the platform, the instance may never be destroyed!<\/li><\/ul><\/li><li>Even if the instance does get garbage collected, this is done in a separate thread, and can (and often does) raise serious synchronization problems and can cause deadlocks.&nbsp; These are&nbsp;<em>very tricky<\/em>&nbsp;to debug, and&nbsp;<em>hard to fix<\/em>, even once you&#8217;ve found the problem.<\/li><li>In short, don&#8217;t use a finalizer where you would use a destructor in C++.&nbsp;&nbsp;<\/li><li>In fact, in most cases, don&#8217;t use a finalizer at all!<\/li><\/ul>\n\n\n\n<p>Instead, what is typically done to reliably release resources in Java is to use a&nbsp;<code><strong>finally&nbsp;<\/strong><\/code>block:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; title: ; quick-code: false; notranslate\" title=\"\">\n\/\/ Allocate resource here.\ntry\n{\n    \/\/ Use resource here\n}\nfinally\n{\n    \/\/ Release resource here\n}\n<\/pre><\/div>\n\n\n<p>By placing the code to release a resource in a&nbsp;<code><strong>finally<\/strong><\/code>&nbsp;block, you ensure that it will get executed whether the code runs successfully, or whether it throws an exception.<\/p>\n\n\n\n<p><strong><em><u>Note:<\/u><\/em><\/strong>&nbsp;There is a similar problem with releasing resources in C++, when exceptions are thrown:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>\/* C++ code *\/<\/strong>\n<strong>Resource rsc = new Resource()\n\/\/ ...\n\/\/ &lt;code that uses the resource, \n\/\/  potentially throwing an exception&gt;\n\/\/ ...\ndelete rsc; \n\/\/ Only executes if no exception is thrown<\/strong><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>In C++, objects are destroyed using class&nbsp;destructors If a C++ object has been allocated using the&nbsp;new&nbsp;operator, it is the programmer&#8217;s responsibility to remember to clean it up, using the&nbsp;delete&nbsp;operator. (In C++, you can allocate objects on the run-time stack, or in static space, in addition to from the heap.)Memory allocation is a very error-prone business [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"parent":57,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"_eb_attr":"","_uag_custom_page_level_css":"","ocean_post_layout":"left-sidebar","ocean_both_sidebars_style":"","ocean_both_sidebars_content_width":0,"ocean_both_sidebars_sidebars_width":0,"ocean_sidebar":"ocs-course-topics-sidebar","ocean_second_sidebar":"0","ocean_disable_margins":"enable","ocean_add_body_class":"","ocean_shortcode_before_top_bar":"","ocean_shortcode_after_top_bar":"","ocean_shortcode_before_header":"","ocean_shortcode_after_header":"","ocean_has_shortcode":"","ocean_shortcode_after_title":"","ocean_shortcode_before_footer_widgets":"","ocean_shortcode_after_footer_widgets":"","ocean_shortcode_before_footer_bottom":"","ocean_shortcode_after_footer_bottom":"","ocean_display_top_bar":"default","ocean_display_header":"default","ocean_header_style":"","ocean_center_header_left_menu":"0","ocean_custom_header_template":"0","ocean_custom_logo":0,"ocean_custom_retina_logo":0,"ocean_custom_logo_max_width":0,"ocean_custom_logo_tablet_max_width":0,"ocean_custom_logo_mobile_max_width":0,"ocean_custom_logo_max_height":0,"ocean_custom_logo_tablet_max_height":0,"ocean_custom_logo_mobile_max_height":0,"ocean_header_custom_menu":"0","ocean_menu_typo_font_family":"0","ocean_menu_typo_font_subset":"","ocean_menu_typo_font_size":0,"ocean_menu_typo_font_size_tablet":0,"ocean_menu_typo_font_size_mobile":0,"ocean_menu_typo_font_size_unit":"px","ocean_menu_typo_font_weight":"","ocean_menu_typo_font_weight_tablet":"","ocean_menu_typo_font_weight_mobile":"","ocean_menu_typo_transform":"","ocean_menu_typo_transform_tablet":"","ocean_menu_typo_transform_mobile":"","ocean_menu_typo_line_height":0,"ocean_menu_typo_line_height_tablet":0,"ocean_menu_typo_line_height_mobile":0,"ocean_menu_typo_line_height_unit":"","ocean_menu_typo_spacing":0,"ocean_menu_typo_spacing_tablet":0,"ocean_menu_typo_spacing_mobile":0,"ocean_menu_typo_spacing_unit":"","ocean_menu_link_color":"","ocean_menu_link_color_hover":"","ocean_menu_link_color_active":"","ocean_menu_link_background":"","ocean_menu_link_hover_background":"","ocean_menu_link_active_background":"","ocean_menu_social_links_bg":"","ocean_menu_social_hover_links_bg":"","ocean_menu_social_links_color":"","ocean_menu_social_hover_links_color":"","ocean_disable_title":"default","ocean_disable_heading":"default","ocean_post_title":"","ocean_post_subheading":"","ocean_post_title_style":"","ocean_post_title_background_color":"","ocean_post_title_background":0,"ocean_post_title_bg_image_position":"","ocean_post_title_bg_image_attachment":"","ocean_post_title_bg_image_repeat":"","ocean_post_title_bg_image_size":"","ocean_post_title_height":0,"ocean_post_title_bg_overlay":0.5,"ocean_post_title_bg_overlay_color":"","ocean_disable_breadcrumbs":"default","ocean_breadcrumbs_color":"","ocean_breadcrumbs_separator_color":"","ocean_breadcrumbs_links_color":"","ocean_breadcrumbs_links_hover_color":"","ocean_display_footer_widgets":"default","ocean_display_footer_bottom":"default","ocean_custom_footer_template":"0","footnotes":""},"class_list":["post-402","page","type-page","status-publish","hentry","entry"],"uagb_featured_image_src":{"full":false,"thumbnail":false,"medium":false,"medium_large":false,"large":false,"1536x1536":false,"2048x2048":false,"ocean-thumb-m":false,"ocean-thumb-ml":false,"ocean-thumb-l":false},"uagb_author_info":{"display_name":"Bryan Higgs","author_link":"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/author\/bryan\/"},"uagb_comment_info":0,"uagb_excerpt":"In C++, objects are destroyed using class&nbsp;destructors If a C++ object has been allocated using the&nbsp;new&nbsp;operator, it is the programmer&#8217;s responsibility to remember to clean it up, using the&nbsp;delete&nbsp;operator. (In C++, you can allocate objects on the run-time stack, or in static space, in addition to from the heap.) Memory allocation is a very error-prone&hellip;","_links":{"self":[{"href":"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/wp-json\/wp\/v2\/pages\/402","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/wp-json\/wp\/v2\/comments?post=402"}],"version-history":[{"count":4,"href":"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/wp-json\/wp\/v2\/pages\/402\/revisions"}],"predecessor-version":[{"id":611,"href":"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/wp-json\/wp\/v2\/pages\/402\/revisions\/611"}],"up":[{"embeddable":true,"href":"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/wp-json\/wp\/v2\/pages\/57"}],"wp:attachment":[{"href":"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/wp-json\/wp\/v2\/media?parent=402"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}