Code segment unload

From Rosetta Code
Code segment unload is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

Some advanced applications, such as memory resident applications, daemons and memory demanding applications unload unrequired parts of the application during use (such as initialization code that will no longer be used again once the application is operational) to free up memory and resources. Demonstrate or explain how to unload an unused section of code from memory.

Note that it is sufficient to flag the memory area as being available for reuse by the memory management system, without the need to demonstrate the zeroing of the bytes and performing a memory shuffle, unless such actions are required to free up the code segment.

Languages that do not have the facility to free up their code segment (such as scripting languages) can be omitted.


Some versions of basic have the facility to delete lines of code:

10 GOSUB 5000: REM call initializer
20 DELETE 5000-9999: REM delete initializer
30 PRINT A: REM show initializer worked
40 LIST: REM show initializer has gone
50 END

5000 REM this is a dummy initializer
5010 LET A=1


The CANCEL statement in COBOL unloads from memory the dynamically-loadable module containing the specified program or entry-point.

CANCEL "foo"


In FreeBASIC, there is no direct way to unload an unused section of code from memory. However, you can free memory used by variables or data.

Here's an example of how you could do it:

p = CALLOC(100, SIZEOF(INTEGER)) ' Reserve memory for 100 integers

'Use memory...

DEALLOC(p) ' Free the memory
p = NULL ' Ensures that the pointer does not point to a freed memory location


The neglect statement in Furor deletes from memory the named function. It is possible because each function is loaded into a dinamycally allocated memory segment.

foo neglect


Although Go supports plug-ins, it is not currently possible to unload them once they have been loaded. This is likely to remain the case as runtime considerations (e.g. stopping goroutines, leaving dangling references) might make it unreliable to do so. However, any objects which the plug-in code creates on the heap will of course be garbage collected when there are no longer any references to them.

In practice, if a Go executable were required to run in a memory-constrained environment, the only option would be to try and divide the executable into a chain of smaller executables which would call the next one in the chain (possibly passing it some parameters) before exiting. Such chaining can be achieved using functions in the os/exec package of the standard library.


# Call anonymous block to do the initialization.

    // Put initialization code here.        
    writeln("Initialization complete.")
) call()

# Garbage collector is now free to recover initialization resources.

writeln("Doing real work.")
// Code to do the real work here.
Initialization complete.
Doing real work.


The situation for Java is as described below in the entry for its sister JVM language, Kotlin.


Julia's functions are compiled and their code allocated memory "just in time" the first time their code is run. Usually, memory used within a function can be dynamically garbage collected once that data is out of scope. To also garbage collect the memory used by a function's code, it would be necessary to define and run a new function with the same name and argument types, which would allow the prior function's code memory to be reclaimed. In practice, this is seldom needed or done, since most memory usage in Julia is for data, not code.


The principal version of Kotlin targets the JVM whose basic code unit is the 'class'. Each class has (and carries a reference to) a classloader which loads it into memory as needed. In most cases the classloaders are created automatically by the system. However, it is possible to create your own to enable classes to be loaded dynamically at runtime.

To my knowledge, there is no explicit mechanism for unloading a class. However, when there are no longer any references to any of its classes or a classloader itself, they will become eligible for garbage collection and the memory they were using will in due course be reclaimed by the garbage collector.

In most cases this is good enough as one of the tenets of the system is that the programmer is relieved from having to worry about memory management.

Even so, situations can arise where one would like a class to be unloaded as quickly as possible and a strategy for dealing with this is to create a classloader which will only load a single class (or a small number of classes) and to then carefully manage the creation of references so that you know when it is safe to unload it (or them). You can then request an immediate garbage collection by calling System.gc(). Note though that this is not guaranteed to work as the request may be overridden by the system if it is deemed to be inopportune.


PARI code can be unloaded like any other C code. But if the code is in the form of a closure (i.e., a GEN object of type t_CLOSURE) then its space should be reclaimed by gerepile or moving ltop if it's at the bottom of the stack.

This is simpler in gp -- just kill the function (or set it to 0, not quite the same but will also cause the memory to be collected).


Perl uses reference counting as its method of managing memory use. As soon as the last reference to a value is released, the value may be destroyed and freed, and handed back to the memory pool. However the exact timing of this action is not under programmer control. Within your program, by using undef and delete, you can hint to Perl that it would now be OK to release this memory. Most importantly, such actions should not be confused with releasing memory back to the operating system. In cases where it is necessary to temporarily allocate a large amount of memory, do so via fork, so when the child process exits the memory is truly freed back to the system.


For compiled programs there is little you could do to reclaim the space of code segments as written to the PE/ELF executable, other than to perhaps "daisy-chain" executables. You could wrap FreeLibrary/dlcose as per OpenOneDLL() in builtins/VM/pcfunc.e.

For interpreted programs however, the code is built and executed in dynamically allocated memory, and in fact "p -test" runs some 60 separate test programs, some of which are deliberately memory-intensive. For each one it allocates a full execution environment, including code space, a call stack, and new heap, and tears it all down and reclaims the memory on completion. That process is, fairly obviously, quite involved and not for the faint hearted, but clearly doable.


The del statement can make objects (both code and data), available for reuse.


Racket has a JIT compiler that translates functions to machine code whenever they are applied. When such a function is garbage-collected, the JITted machine code is released or re-used with it. Therefore, to reclaim some executable code segment, simply drop references to the function.


(formerly Perl 6) In general, there is no specific mechanism to do a timely destruction of an object, be it code, data, variables, whatever. Raku does automatic garbage collection on objects that are no longer being used. Unlike Perl, from which Raku is loosely derived, it doesn't use reference counting to track when memory may be garbage collected as that tends to be very difficult to get correct and performant in multi-threaded applications. Rather it performs a "reachability analysis" to determine when objects can be evicted from memory and safely removed.

Raku objects can provide a "DESTROY" method, but you cannot be sure when (if ever) it will be called. Raku tends to not be very memory frugal. If there is lots of memory to be had, it will cheerfully use lots of it. It gets more aggressive about conserving if memory is tight, but usually will trade memory for performance. If and when garbage collection has run, the freed memory is then available to to the general OS pool for any process to claim.

There are some specific details that will allow some finer control of garbage collection in special circumstances, but the average Raku programmer will not need to know about or deal with them.


When using REXX in the (VM) CMS environment, the use of   NUCXDROP   can be used to release memory (virtual storage) that a REXX program is using   (when previously loaded into virtual memory via   NUCXLOAD).


As the situation for Scala in a JVM concerned, the in the entry for its sister JVM language, #Kotlin applies too.


Smalltalk runs in an image that can be saved to disk as a snapshot, and later loaded into memory and resumed. The VM (there are multiple implementations) performs garbage collection on this image, and usually also compacts it so that un-needed memory can be returned to the OS. The snapshot-resume cycle might do other kinds of compaction that reduces the image size even further.

The different phases of the GC can be explicitly invoced to reclaim unused memory immediately, but it does not guarantee the reclaimed memory is deemed excessive and therefore will be returned to the OS.


Tcl can release memory associated with a program in three ways.

Releasing commands
The memory associated with a particular command can be released back to the general memory pool by deleting the command. This is done by either creating a new command with the same name, or by using rename to change the command's name to the empty string.
rename exampleCmd ""
Releasing loaded extensions
The memory associated with a loaded extension can be released by using unload, provided the extension has registered a handler function (this is relatively uncommon). Once the handler function has run (which gives the extension an opportunity to destroy any commands and other callbacks it has created), the underlying library will be removed from memory with dlclose() (on Unix) or FreeLibrary() (on Windows). This completely removes the program code concerned, as well as returning the other ancillary memory to the general pool.
unload theLibrary.dll
Releasing an entire interpreter
Provided an interpreter is not the root interpreter in its thread, you can delete it from an ancestor interpreter, which releases all the memory associated with it back into the general memory pool.
interp delete theChildInterpreter


It is not currently possible to unload code from a running Wren script.

However, what you can do is to place code that will only be run once, such as initialization code, into a function and then call that. Functions (as opposed to class methods) are first class objects in Wren and will be garbage collected when there are no longer any references to them. This doesn't usually occur immediately but you can request an immediate collection by calling the System.gc method.