finalizer

finalizer(x, function)

Register a function f(x) to be called when there are no program-accessible references to x. The behavior of this function is unpredictable if x is of a bits type.

Examples

  1. Register a finalizer function:

    julia> obj = "Hello, World!";
    julia> finalizer(obj, () -> println("Finalizer called for $obj"))

    This example registers a finalizer function that will be called when there are no program-accessible references to the object obj.

  2. Perform cleanup operations:

    julia> struct Resource
               id::Int
           end
    
    julia> function cleanup(resource::Resource)
               println("Cleaning up resource with id: $(resource.id)")
           end
    
    julia> res = Resource(123);
    julia> finalizer(res, () -> cleanup(res))

    In this example, a finalizer function cleanup is registered for the Resource object res. When there are no references to res, the finalizer function will be called, allowing for cleanup operations to be performed.

  3. Handle complex objects:

    julia> mutable struct ComplexObject
               data::Array{Int, 2}
           end
    
    julia> function cleanup(obj::ComplexObject)
               println("Cleaning up ComplexObject with data: $(obj.data)")
           end
    
    julia> obj = ComplexObject([1 2 3; 4 5 6]);
    julia> finalizer(obj, () -> cleanup(obj))

    This example demonstrates how a finalizer can be used with more complex objects. The cleanup function is registered as the finalizer for the ComplexObject obj. When obj becomes unreferenced, the finalizer function will be called, allowing for cleanup or additional actions to be performed.

Note: It's important to avoid using the finalizer function with objects of bits types, as the behavior of the finalizer function can be unpredictable in such cases.

See Also

assert, backtrace, code_llvm, code_lowered, code_native, code_typed, code_warntype, :@which, compilecache, current_module, eval, finalize, finalizer, fullname, function_module, function_name, include_dependency, InterruptException, invoke, isconst, isdefined, isgeneric, methodswith, method_exists, module_name, module_parent, require, subtypes, unsafe_load, workspace, __precompile__,

User Contributed Notes

Add a Note

The format of note supported is markdown, use triple backtick to start and end a code block.

*Required Field
Details

Checking you are not a robot: