」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > Java Cleaners:管理外部資源的現代方法

Java Cleaners:管理外部資源的現代方法

發佈於2024-08-21
瀏覽:995

Code for this article can be found on GitHub.
If you’re the type of programmer who likes to understand the internals of how things work before seeing examples,
you can jump directly to Cleaners behind the scene after the introduction.

  • Introduction
  • Simple Cleaner in action
  • Cleaners, the right way
  • Cleaners, the effective way
  • Cleaners behind the scene

Introduction

Think of a scenario where you have an object that holds references to external resources (files, sockets, and so on). And you want to have control over how these resources are released once the holding object is no longer active/accessible, how do you achieve that in Java?. Prior to Java 9 programmers could use a finalizer by overriding the Object’s class finalize() method. Finalizers have many disadvantages, including being slow, unreliable and dangerous. It is one of those features that are hated by both those who implement the JDK and those who use it.

Since Java 9, Finalizers have been deprecated and programmers have a better option to achieve this in Cleaners, Cleaners provide a better way to manage and handle cleaning/finalizing actions. Cleaners work in a pattern where they let resource holding objects register themselves and their corresponding cleaning actions. And then Cleaners will call the cleaning actions once these objects are not accessible by the application code.
This is not the article to tell you why Cleaners are better than Finalizers, though I will briefly list some of their differences.

Finalizers Vs Cleaners

Finalizers Cleaners
Finalizers are invoked by one of Garbage Collector’s threads, you as a programmer don’t have control over what thread will invoke your finalizing logic Unlike with finalizers, with Cleaners, programmers can opt to have control over the thread that invokes the cleaning logic.
Finalizing logic is invoked when the object is actually being collected by GC Cleaning logic is invoked when the object becomes Phantom Reachable, that is our application has no means to access it anymore
Finalizing logic is part of the object holding the resources Cleaning logic and its state are encapsulated in a separate object.
No registration/deregistration mechanism Provides means for registering cleaning actions and explicit invocation/deregistration

Simple Cleaner in action

Enough chit-chats let us see Cleaners in action.

ResourceHolder

import java.lang.ref.Cleaner;

public class ResourceHolder {
 private static final Cleaner CLEANER = Cleaner.create();
        public ResourceHolder() {
            CLEANER.register(this, () -> System.out.println("I'm doing some clean up"));
        }
        public static void main(String... args) {
            ResourceHolder resourceHolder = new ResourceHolder();
            resourceHolder = null;
            System.gc();
        }}

Few lines of code but a lot is happening here, Let us break it down

  1. The constant CLEANER is of type java.lang.ref.Cleaner, as you can tell from its name, this is the central and starting point of the Cleaners feature in Java. The CLEANER variable is declared as static as it should be, Cleaners should never be instance variables, they should be shared across different classes as much as possible.
  2. In the constructor, instances of ResourceHolder are registering themselves to the Cleaner along with their cleaning action, the cleaning action is a Runnable job that the Cleaner guarantees to invoke at most once (at most once, meaning it is possible not to run at all). By calling Cleaner’s register() method, these instances are basically saying two things to the Cleaner
    • Keep track of me as long as I live
    • And once I am no longer active (Phantom Reachable), please do your best and invoke my cleaning action.
  3. In the main method we instantiate an object of ResourceHolder and immediately set its variable to null, since the object has only one variable reference, our application can no longer access the object, i.e., it has become Phantom Reachable
  4. We call System.gc() to request JVM to run the Garbage Collector, consequentially this will trigger the Cleaner to run the cleaning action. Typically, you don’t need to call System.gc() but as simple as our application, we need to facilitate the Cleaner to run the action

Run the application, and hopefully you see I’m doing some clean up somewhere in your standard output.

? CAUTION
We started with the simplest possible way to use Cleaners, so we can demonstrate its usage in a simplified way, bear in mind though this is neither effective nor the right way to use Cleaners

Cleaners, the right way

Our first example was more than good enough to see Cleaners in action,
but as we warned, it is not the right way to use Cleaners in a real application.
Let’s see what is wrong with what we did.

  1. We initiated a Cleaner object as a class member of the ResourceHolder: As we mentioned earlier Cleaners should be shared across Classes and should not belong to individual classes, reason behind being each Cleaner instance maintains a thread, which is a limited native resource, and you want to be cautious when you consume native resources.
    In a real application, we typically get a Cleaner object from a utility or a Singleton class like

      private static CLEANER = AppUtil.getCleaner();
    
  2. We passed in a lambda as our Cleaning action: You should NEVER pass in a lambda as your cleaning action.
    To understand why,
    let us refactor our previous example by extracting the printed out message and make it an instance variable

    ResourceHolder

    public class ResourceHolder {
       private static final Cleaner CLEANER = Cleaner.create();
       private final String cleaningMessage = "I'm doing some clean up";
       public ResourceHolder() {
           CLEANER.register(this, () -> System.out.println(cleaningMessage));
       }
    }
    

    Run the application and see what happens.
    I will tell you what happens,
    the cleaning action will never get invoked no matter how many times you run your application.
    Let us see why

    • Internally, Cleaners make use of PhantomReference and ReferenceQueue to keep track of registered objects, once an object becomes Phantom Reachable the ReferenceQueue will notify the Cleaner and the Cleaner will use its thread to run the corresponding cleaning action.
    • By having the lambda accessing the instance member we’re forcing the lambda to hold the this reference(of ResourceHolder instance), because of this the object will never ever become Phantom Reachable because our Application code still has reference to it.

    ? NOTE
    If you still wonder how in our first example, the cleaning action is invoked despite having it as a lambda. The reason is, the lambda in the first example does not access any instance variable, and unlike inner classes, Lambdas won’t implicitly hold the containing object reference unless they’re forced to.

    The right way is to encapsulate your cleaning action together with the state it needs in a static nested class.

    ? Warning
    Don’t use inner class anonymous or not, it is worse than using lambda because an inner class instance would hold a reference to the outer class instance regardless of whether they access their instance variable or not.

  3. We didn't make use of the return value from the Cleaner.create(): The create() actually returns something very important.a Cleanable object, this object has a clean() method that wraps your cleaning logic, you as a programmer can opt to do the cleanup yourself by invoking the clean() method. As mentioned earlier, another thing that makes Cleaners superior to Finalizers is that you can actually deregister your cleaning action. The clean() method actually deregisters your object first, and then it invokes your cleaning action, this way it guarantees the at-most once behavior.

Now let us improve each one of these points and revise our ResourceHolder class

ResourceHolder

import java.lang.ref.Cleaner;

public class ResourceHolder {

    private final Cleaner.Cleanable cleanable;
    private final ExternalResource externalResource;

    public ResourceHolder(ExternalResource externalResource) {
        cleanable = AppUtil.getCleaner().register(this, new CleaningAction(externalResource));
        this.externalResource = externalResource;
    }

//    You can call this method whenever is the right time to release resource
    public void releaseResource() {
        cleanable.clean();
    }

    public void doSomethingWithResource() {
        System.out.printf("Do something cool with the important resource: %s \n", this.externalResource);
    }

    static class CleaningAction implements Runnable {
        private ExternalResource externalResource;

        CleaningAction(ExternalResource externalResource) {
            this.externalResource = externalResource;
        }

        @Override
        public void run() {
//          Cleaning up the important resources
            System.out.println("Doing some cleaning logic here, releasing up very important resource");
            externalResource = null;
        }
    }

    public static void main(String... args) {
        ResourceHolder resourceHolder = new ResourceHolder(new ExternalResource());
        resourceHolder.doSomethingWithResource();
/*
        After doing some important work, we can explicitly release
        resources/invoke the cleaning action
*/
        resourceHolder.releaseResource();
//      What if we explicitly invoke the cleaning action twice?
        resourceHolder.releaseResource();
    }
}

ExternalResource is our hypothetical resource that we want to release when we’re done with it.
The cleaning action is now encapsulated in its own class, and we make use of the CleaniangAction object, we call it’s clean() method in the releaseResources() method to do the cleanup ourselves.
As stated earlier, Cleaners guarantee at most one invocation of the cleaning action, and since we call the clean() method explicitly the Cleaner will not invoke our cleaning action except in the case of a failure like an exception is thrown before the clean method is called, in this case the Cleaner will invoke our cleaning action when the ResourceHolder object becomes Phantom Reachable, that is we use the Cleaner as our safety-net, our backup plan when the first plan to clean our own mess doesn’t work.

❗ IMPORTANT
The behavior of Cleaners during System.exit is implementation-specific. With this in mind, programmers should always prefer to explicitly invoke the cleaning action over relying on the Cleaners themselves..

Cleaners, the effective way

By now we’ve established the right way to use Cleaners is to explicitly call the cleaning action and rely on them as our backup plan.What if there’s a better way? Where we don’t explicitly call the cleaning action, and the Cleaner stays intact as our safety-net.
This can be achieved by having the ResourceHolder class implement the AutoCloseable interface and place the cleaning action call in the close() method, our ResourceHolder can now be used in a try-with-resources block. The revised ResourceHolder should look like below.

ResourceHolder

import java.lang.ref.Cleaner.Cleanable;

public class ResourceHolder implements AutoCloseable {

    private final ExternalResource externalResource;

    private final Cleaner.Cleanable cleanable;

    public ResourceHolder(ExternalResource externalResource) {
        this.externalResource = externalResource;
        cleanable = AppUtil.getCleaner().register(this, new CleaningAction(externalResource));
    }

    public void doSomethingWithResource() {
        System.out.printf("Do something cool with the important resource: %s \n", this.externalResource);
    }
    @Override
    public void close() {
        System.out.println("cleaning action invoked by the close method");
        cleanable.clean();
    }

    static class CleaningAction implements Runnable {
        private ExternalResource externalResource;

        CleaningAction(ExternalResource externalResource) {
            this.externalResource = externalResource;
        }

        @Override
        public void run() {
//            cleaning up the important resources
            System.out.println("Doing some cleaning logic here, releasing up very important resources");
            externalResource = null;
        }
    }

    public static void main(String[] args) {
//      This is an effective way to use cleaners with instances that hold crucial resources
        try (ResourceHolder resourceHolder = new ResourceHolder(new ExternalResource(1))) {
            resourceHolder.doSomethingWithResource();
            System.out.println("Goodbye");
        }
/*
    In case the client code does not use the try-with-resource as expected,
    the Cleaner will act as the safety-net
*/
        ResourceHolder resourceHolder = new ResourceHolder(new ExternalResource(2));
        resourceHolder.doSomethingWithResource();
        resourceHolder = null;
        System.gc(); // to facilitate the running of the cleaning action
    }
}


Cleaners behind the scene

? NOTE
To understand more and see how Cleaners work, checkout the OurCleaner class under the our_cleaner package that imitates the JDK real implementation of Cleaner. You can replace the real Cleaner and Cleanable with OurCleaner and OurCleanable respectively in all of our examples and play with it.

Let us first get a clearer picture of a few, already mentioned terms, phantom-reachable, PhantomReference and ReferenceQueue

  • Consider the following code

    Object myObject = new Object();
    

    In the Garbage Collector (GC) world the created instance of Object is said to be strongly-reachable, why? Because it is alive, and in-use i.e., Our application code has a reference to it that is stored in the myObject variable, assume we don’t set another variable and somewhere in our code this happens

    myObject = null;
    

    The instance is now said to be unreachable, and is eligible for reclamation by the GC.
    Now let us tweak the code a bit

    Object myObject = new Object();
    PhantomReference reference = new PhantomReference(myObject, null);
    

    Reference is a class provided by JDK to represent reachability of an object during JVM runtime, the object a Reference object is referring to is known as referent, PhantomReference is a type(also an extension) of Reference whose purpose will be explained below in conjunction with ReferenceQueue.
    Ignore the second parameter of the constructor for now, and again assume somewhere in our code this happens again

    myObject = null;
    

    Now our object is not just unreachable it is phantom-reachable because no part of our application code can access it, AND it is a referent of a PhantomReference object.

  • After the GC has finalized a phantom-reachable object, the GC attaches its PhantomReference object(not the referent) to a special kind of queue called ReferenceQueue. Let us see how these two concepts work together

    Object myObject = new Object();
    ReferenceQueue queue = new ReferenceQueue();
    PhantomReference reference1 = new PhantomReference(myObject, queue);
    myObject = null;
    PhantomReference reference2 = (PhantomReference)queue.remove()
    

    We supply a ReferenceQueue when we create a PhantomReference object so the GC knows where to attach it when its referent has been finalized. The ReferenceQueue class provides two methods to poll the queue, remove(), this will block when the queue is empty until the queue has an element to return, and poll() this is non-blocking, when the queue is empty it will return null immediately.
    With that explanation, the code above should be easy to understand, once myObject becomes phantom-reachable the GC will attach the PhantomReference object to queue and we get it by using the remove() method, that is to say reference1 and reference2 variables refer to the same object.

Now that these concepts are out of the way, let’s explain two Cleaner-specific types

  1. For each cleaning action, Cleaner will wrap it in a Cleanable instance, Cleanable has one method, clean(), this method ensure the at-most once invocation behavior before invoking the cleaning action.
  2. PhantomCleanable implements Cleanable and extends PhantomReference, this class is the Cleaner’s way to associate the referent(resource holder) with their cleaning action

From this point on understanding the internals of Cleaner should be straight forward.

Cleaner Life-Cycle Overview

Java Cleaners: The Modern Way to Manage External Resources

Let us look at the life-cycle of a Cleaner object

  • The static Cleaner.create() method instantiates a new Cleaner but it also does a few other things

    • It instantiates a new ReferenceQueue, that the Cleaner objet’s thread will be polling
    • It creates a doubly linked list of PhantomCleanable objects, these objects are associated with the queue created from the previous step.
    • It creates a PhantomCleanable object with itself as the referent and empty cleaning action.
    • It starts a daemon thread that will be polling the ReferenceQueue as long as the doubly linked list is not empty.

    By adding itself into the list, the cleaner ensures that its thread runs at least until the cleaner itself becomes unreachable

  • For each Cleaner.register() call, the cleaner creates an instance of PhantomCleanable with the resource holder as the referent and the cleaning action will be wrapped in the clean() method, the object is then added to the aforementioned linked list.

  • The Cleaner’s thread will be polling the queue, and when a PhantomCleanable is returned by the queue, it will invoke its clean() method. Remember the clean() method only calls the cleaning action if it manages to remove the PhantomCleanable object from the linked list, if the PhantomCleanable object is not on the linked list it does nothing

  • The thread will continue to run as long as the linked list is not empty, this will only happen when

    • All the cleaning actions have been invoked, and
    • The Cleaner itself has become phantom-reachable and has been reclaimed by the GC
版本聲明 本文轉載於:https://dev.to/ahmedjaad/java-cleaners-the-modern-way-to-manage-external-resources-4d4?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>
  • Bootstrap 4 Beta 中的列偏移發生了什麼事?
    Bootstrap 4 Beta 中的列偏移發生了什麼事?
    Bootstrap 4 Beta:列偏移的刪除和恢復Bootstrap 4 在其Beta 1 版本中引入了重大更改柱子偏移了。然而,隨著 Beta 2 的後續發布,這些變化已經逆轉。 從 offset-md-* 到 ml-auto在 Bootstrap 4 Beta 1 中, offset-md-*...
    程式設計 發佈於2024-11-16
  • 大批
    大批
    方法是可以在物件上呼叫的 fns 數組是對象,因此它們在 JS 中也有方法。 slice(begin):將陣列的一部分提取到新數組中,而不改變原始數組。 let arr = ['a','b','c','d','e']; // Usecase: Extract till index ...
    程式設計 發佈於2024-11-16
  • 在 Go 中使用 WebSocket 進行即時通信
    在 Go 中使用 WebSocket 進行即時通信
    构建需要实时更新的应用程序(例如聊天应用程序、实时通知或协作工具)需要一种比传统 HTTP 更快、更具交互性的通信方法。这就是 WebSockets 发挥作用的地方!今天,我们将探讨如何在 Go 中使用 WebSocket,以便您可以向应用程序添加实时功能。 在这篇文章中,我们将介绍: WebSoc...
    程式設計 發佈於2024-11-16
  • 如何在 PHP 中組合兩個關聯數組,同時保留唯一 ID 並處理重複名稱?
    如何在 PHP 中組合兩個關聯數組,同時保留唯一 ID 並處理重複名稱?
    在 PHP 中組合關聯數組在 PHP 中,將兩個關聯數組組合成一個數組是常見任務。考慮以下請求:問題描述:提供的代碼定義了兩個關聯數組,$array1和$array2。目標是建立一個新陣列 $array3,它合併兩個陣列中的所有鍵值對。 此外,提供的陣列具有唯一的 ID,而名稱可能重疊。要求是建構一...
    程式設計 發佈於2024-11-16
  • 為什麼 Visual Studio 2010 中 x86 和 x64 的浮點運算不同?
    為什麼 Visual Studio 2010 中 x86 和 x64 的浮點運算不同?
    x86 與x64 之間的浮點算術差異在Visual Studio 2010 中,x86 與x64 版本之間的浮點算術存在明顯差異當比較某些表達式的值時出現。這種差異體現在以下程式碼:float a = 50.0f; float b = 65.0f; float c = 1.3f; float d =...
    程式設計 發佈於2024-11-15
  • 如何提高帶有通配符的 MySQL LIKE 運算子的效能?
    如何提高帶有通配符的 MySQL LIKE 運算子的效能?
    MySQL LIKE 運算子最佳化MySQL LIKE 運算子最佳化問題:使用萬用字元(例如'%test% ')?答案: 是的,在查詢中使用特定模式時,MySQL 可以最佳化LIKE 運算子的效能。 前綴通配符: 如果您的查詢類似於 foo LIKE 'abc%' 或...
    程式設計 發佈於2024-11-15
  • 如何使用 PHP 透過 POST 向外部網站發送資料?
    如何使用 PHP 透過 POST 向外部網站發送資料?
    在PHP 中透過POST 重新導向並傳送資料在PHP 中,您可能會遇到需要將使用者重新導向到外部的情況網站並透過POST 將資料傳遞到該網站。與 HTML 表單不同,PHP 本身並不支援此行為。 GET 與POST在Web 開發中,有兩種​​主要方法用於從來源發送資料到目的地: GET:資料作為查詢...
    程式設計 發佈於2024-11-15
  • 如何使用 GCC 捕捉 Linux 中的分段錯誤?
    如何使用 GCC 捕捉 Linux 中的分段錯誤?
    捕獲Linux 中的分段錯誤問:我在第三方庫中遇到分段錯誤,但我無法解決根本問題。是否有跨平台或特定於平台的解決方案來使用 gcc 捕獲 Linux 中的這些錯誤? A:Linux 允許將分段錯誤作為異常處理。當程式遇到此類故障時,它會收到 SIGSEGV 訊號。透過設定訊號處理程序,您可以攔截此訊...
    程式設計 發佈於2024-11-15
  • 如何在不建立實例的情況下存取Go結構體的類型?
    如何在不建立實例的情況下存取Go結構體的類型?
    在不創建物理結構的情況下訪問Reflect.Type在Go 中,動態加載問題的解決方案需要訪問結構的類型,而無需物理創建它們。雖然現有的解決方案要求在類型註冊之前建立結構體並清除零,但有一種更有效的方法。 人們可以利用 reflect.TypeOf((*Struct)(nil)).Elem()手術。...
    程式設計 發佈於2024-11-15
  • Java中如何有效率地將整數轉換為位元組數組?
    Java中如何有效率地將整數轉換為位元組數組?
    Java 中整數到位元組數組的高效轉換將整數轉換為位元組數組可用於多種目的,例如網路傳輸或資料儲存。有多種方法可以實現此轉換。 ByteBuffer 類別:一個有效的方法是使用 ByteBuffer 類別。 ByteBuffer 是一個儲存二進位資料並提供各種操作來操縱它的緩衝區。使用 ByteBu...
    程式設計 發佈於2024-11-15
  • 如何在 Go 中按多個欄位對結構體切片進行排序?
    如何在 Go 中按多個欄位對結構體切片進行排序?
    按多個欄位對切片物件進行排序依多個條件排序考慮以下Parent 和Child 結構:type Parent struct { id string children []Child } type Child struct { id string }假設我們有一個帶有...
    程式設計 發佈於2024-11-15
  • Qt 線程與 Python 線程:我應該在 PyQt 應用程式中使用哪個?
    Qt 線程與 Python 線程:我應該在 PyQt 應用程式中使用哪個?
    PyQt 應用程式中的線程:Qt 線程與Python 線程尋求使用PyQt 創建響應式GUI 應用程式的開發人員經常遇到到執行的挑戰長時間運行的任務而不影響UI 的功能。一種解決方案是使用單獨的執行緒來完成這些任務。這就提出了使用 Qt 執行緒還是原生 Python 執行緒模組的問題。 Qt 執行緒...
    程式設計 發佈於2024-11-15
  • 為什麼我的PHP提交按鈕沒有觸發回顯和表格顯示?
    為什麼我的PHP提交按鈕沒有觸發回顯和表格顯示?
    PHP 提交按鈕困境:不可用的回顯和表格您的程式碼打算在點擊「提交」按鈕時顯示回顯和表格在PHP 表單上。但是,您遇到了這些元素仍然隱藏的問題。這是因為您使用 if(isset($_POST['submit'])) 來控制這些元素的顯示,但提交按鈕缺少 name 屬性。 解決方案:提...
    程式設計 發佈於2024-11-15
  • 為什麼我的 @font-face EOT 字型無法在 Internet Explorer 中透過 HTTPS 載入?
    為什麼我的 @font-face EOT 字型無法在 Internet Explorer 中透過 HTTPS 載入?
    @font-face EOT 無法透過HTTPS 載入:解決方案在Internet 中與@font-face EOT 檔案在Internet 中無法透過HTTPS 載入的問題在Explorer 版本7、8 和9 中,使用者發現無論HTTPS 上包含的HTML 頁面的託管狀態如何,問題仍然存在。經過實...
    程式設計 發佈於2024-11-15
  • 為什麼透過 Makefile 運行 Go 程式時出現「權限被拒絕」錯誤?
    為什麼透過 Makefile 運行 Go 程式時出現「權限被拒絕」錯誤?
    權限被拒絕:調查「go run」和Makefile 呼叫之間的差異透過Makefile 執行Go 程式時遇到權限被拒絕錯誤可能會令人困惑。此問題源自於 GNU make 或其 gnulib 元件中的錯誤。根本原因在於系統 PATH 中存在一個名為「go」的目錄,該目錄位於實際 Go 執行檔所在的目錄...
    程式設計 發佈於2024-11-15

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3