Finalisers

A finaliser is the code that runs when a value of a type dies. It is the counterpart of the constructor, and for a type that owns something outside its own storage, a file unit, a C resource, a slot in a pool, it is where that thing is released. This lesson follows a handle through a run: made in a scope, made in a block, copied over, passed to an intent(out) dummy and deallocated, with the finaliser printing every time it runs. Two gaps in this build turn up in the same run and are shown with their real output.

The FINAL binding

final :: release in the type's binding list names a module procedure with exactly one dummy argument, the object, declared type(handle), intent(inout). It is not a generic and it is not called by name; the runtime calls it. A type may have several finalisers for different ranks, and an array of the type is finalised element by element in principle.

The module counts opens and closes in two module variables, so the run tells its own story without a debugger.

The file final1.f90:

module pool implicit none private public :: handle, acquire, take, report integer :: n_open = 0 integer :: n_close = 0 type :: handle integer :: id = 0 contains final :: release end type handle contains subroutine acquire(h, id) type(handle), intent(inout) :: h integer, intent(in) :: id h%id = id n_open = n_open + 1 print '(a,i0,a,i0)', 'open id=', id, ' open = ', n_open end subroutine acquire subroutine release(self) type(handle), intent(inout) :: self n_close = n_close + 1 print '(a,i0,a,i0)', 'close id=', self%id, ' closed = ', n_close end subroutine release subroutine take(h) type(handle), intent(out) :: h print '(a)', 'in take: the argument is undefined on entry' h%id = 99 end subroutine take subroutine report() print '(a,i0,a,i0)', 'totals: opened = ', n_open, ' closed = ', n_close end subroutine report end module pool program findemo use pool implicit none call run() call report() contains subroutine run() type(handle) :: a, b type(handle), allocatable :: tmp call acquire(a, 1) call acquire(b, 2) block type(handle) :: inner call acquire(inner, 3) print '(a)', 'block ends' end block a = b print '(a)', 'a was assigned over' call take(b) print '(a)', 'take returned' allocate(tmp) call acquire(tmp, 4) print '(a)', 'deallocating tmp' deallocate(tmp) end subroutine run end program findemo

gfortran -Wall -Wextra -std=f2018 final1.f90 -o final1
./final1

open id=1 open = 1
open id=2 open = 2
open id=3 open = 3
block ends
close id=3 closed = 1
close id=1 closed = 2
a was assigned over
close id=2 closed = 3
in take: the argument is undefined on entry
take returned
open id=4 open = 4
deallocating tmp
close id=4 closed = 4
close id=99 closed = 5
close id=2 closed = 6
totals: opened = 4 closed = 6

The timeline of a run

Read the output beside the source and every line has a cause. The three opens are the three acquire calls. close id=3 is the end of the block, which is the end of the scope of inner. close id=1 is a = b: the old value of a is destroyed before the copy goes in, which is why the line comes before "a was assigned over". close id=2 before "in take" is the intent(out) dummy: entering the subroutine finalises the value the caller passed, and the dummy then starts undefined.

The last three lines are the end of run. close id=4 is the deallocate(tmp). close id=99 is the local h inside take, which owned a handle of its own. And close id=2 is a, which held a copy of what b had. The finaliser runs when a scope ends, not when a resource is first seen.

Why the counts differ

Four opens and six closes. That is not a bug in the counting: a finaliser runs per value, and a value can be a copy. b was finalised when take began, and a held a copy of the same id and was finalised when run ended, so one open was closed twice. The handle built inside take was never counted as an open, because acquire was not called for it.

The lesson for a real resource is to count what you own, not what you see: an id that appears twice must not be released twice. A finaliser that closes a file unit or frees a C pointer has to survive being called on a copy, which means the type needs a flag, an owner field, or a reference count, exactly as in C++.

Scalar and array

The standard finalises the elements of an array and a scalar alike. This compiler does not, and the difference is easy to see in one program:

The file final2.f90:

module pool_arr implicit none private public :: handle type :: handle integer :: id = 0 contains final :: release end type handle contains subroutine release(self) type(handle), intent(inout) :: self print '(a,i0)', 'finaliser ran for id=', self%id end subroutine release end module pool_arr program arrdemo use pool_arr implicit none type(handle), allocatable :: arr(:) class(handle), allocatable :: one allocate(arr(2)) arr(1)%id = 1 arr(2)%id = 2 print '(a)', 'deallocating the array' deallocate(arr) print '(a)', 'deallocated the array' allocate(handle :: one) one%id = 3 print '(a)', 'deallocating the scalar' deallocate(one) print '(a)', 'deallocated the scalar' end program arrdemo

gfortran -Wall -Wextra -std=f2018 final2.f90 -o final2
./final2

deallocating the array
deallocated the array
deallocating the scalar
finaliser ran for id=3
deallocated the scalar

The array was deallocated and not one element was finalised; the scalar printed its line. A program that relies on a finaliser to close a resource stored in an array of the type leaks it on this compiler, and the leak is silent. The workaround is explicit: loop over the array and release each element through a binding or a plain subroutine before the array dies, and keep the finaliser for the scalar case.

The main-program variable

The other gap is the top level. A value declared in the main program is not finalised when the program ends: gfortran 15.2.0 simply leaves the program. The example above puts its handles in a contained subroutine for that reason, and a program that relies on the last writes of a finaliser has to do the same, or close things explicitly before end program.

Both gaps belong to the compiler, not to the language, so a program that depends on them should be tested on the compiler it will be built with. A release path that also works when the finaliser does not run is the robust design in any case.

A finaliser with two arguments

The signature is checked where the binding is written:

module pool_bad implicit none type :: handle integer :: id = 0 contains final :: release end type handle contains subroutine release(self, tag) type(handle), intent(inout) :: self, tag print *, 'closing', self%id end subroutine release end module pool_bad

gfortran -Wall -Wextra -std=f2018 -c badfin.f90

badfin.f90:6:20:

6 | final :: release
| 1
Error: FINAL procedure at (1) must have exactly one argument

One argument, of the type itself: a finaliser receives the object and nothing else. A second argument would be a parameter, and the runtime has no way to supply one, so the language forbids it rather than leaving a call that could never be made.

What to release in a finaliser

Release what the type owns and nothing else: a unit it opened, a C block it allocated, a row it reserved in a shared array. Do not print from a finaliser in production code, do not allocate there in the hope of replacing the value, and do not touch another value of the same type, because the order between two finalisations in one scope is not specified.

A finaliser that can run twice, as in the counting example, needs the same guard a C++ destructor needs. The cheapest is an id of zero meaning nothing to release: the release procedure tests it, does nothing when it is zero, and sets it to zero after releasing. With that guard the double close in the first program would be a no-op instead of a second release of the same resource.

Exercises

  1. Add the zero-id guard to release and run the program again. Which of the six closes disappear from the count?
  2. Move the block in run to the top level of the main program. Which close lines are lost, and why?
  3. Write call take(a) instead of call take(b). Which id is closed before the message, and which at the end?
  4. Declare type(handle) :: arr(2) in run and fill it. Are the elements finalised at the end of run?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does final :: release in a type bind?

    Answer

    A subroutine with one dummy of the type, run when a value dies

    The finaliser is called by the runtime, not by name.

  2. How is the dummy of a finaliser declared?

    Answer

    type(t), intent(inout)

    One argument, the object itself, writable.

  3. What happens to the old value of a variable on assignment?

    Answer

    It is finalised before the new value goes in

    The assignment destroys the old value.

  4. What does this program print? module m implicit none type :: t integer :: n = 0 contains final :: bye end type t contains subroutine bye(self) type(t), intent(inout) :: self print *, "bye", self%n end subroutine bye end module m program p use m implicit none call run() contains subroutine run() block type(t) :: v v%n = 2 print *, "alive", v%n end block print *, "after" end subroutine run end program p

    Answer

    alive 2, bye 2, after

    The block ends before "after" is printed.

  5. Why can more closes than opens appear in the first program?

    Answer

    A finaliser runs per value, and a copy carries the same id

    One resource can end up in two values.

  6. What does gfortran 15.2.0 do with the elements of an array of a finalisable type on DEALLOCATE?

    Answer

    It does not finalise them; the scalar case works

    The lesson shows the run with no finaliser line for the array.

  7. What happens to a value of a finalisable type declared in the main program at the end?

    Answer

    gfortran 15.2.0 does not finalise it

    The lesson keeps its values in a contained subroutine.

  8. What does gfortran say about a finaliser with two dummy arguments?

    Answer

    Error: FINAL procedure must have exactly one argument

    The runtime can only supply the object.

  9. Why does a finaliser that closes a resource need a guard?

    Answer

    It can run for a copy, so the same resource could be released twice

    An id of zero meaning "nothing to release" is the cheapest guard.

  10. What should a finaliser never do?

    Answer

    Print, allocate a replacement or depend on the order of other finalisations

    It releases ownership and nothing else.

The programs on this page were built with GNU Fortran (Alpine 15.2.0) 15.2.0 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev

Banner image