Julia Resource Safety
Resource safety is code that releases a resource such as an open file even when an error stops the work. The release step runs on every path out of the block.
A do block closes the file for you
The block writes hello to notes.txt. The file stays readable after the block ends.
open("notes.txt", "w") do io
write(io, "hello")
end
println(read("notes.txt", String))A finally step runs even when the work fails
The work writes start and then fails. The finally step still closes the file and sets the flag.
done = Ref(false)
function risky_work()
io = open("work.txt", "w")
try
write(io, "start")
error("stop")
finally
close(io)
done[] = true
end
end
try
risky_work()
catch
nothing
end
println(done[])
println(read("work.txt", String))A finalizer runs when collection removes the object
The guard object is left with no owner. A forced collection runs its finalizer and sets the flag.
mutable struct Guard
name::String
end
seen = Ref(false)
function make_guard(flag)
g = Guard("g")
finalizer(g) do _
flag[] = true
end
return nothing
end
make_guard(seen)
GC.gc()
println(seen[])Example
open("safe.txt", "w") do io
write(io, "safe")
end
cleaned = Ref(false)
function read_safe()
io = open("safe.txt", "r")
try
return read(io, String)
finally
close(io)
cleaned[] = true
end
end
text = read_safe()
println(text)
println(cleaned[])Key points
- Do-block: a file opened with a do block closes when the block ends.
- Try-finally: a finally step runs whether the try block works or fails.
- Close: closing a file frees it so other code can read it.
- Finalizer: a cleanup function that runs when an object is collected.
- Forced collection: GC.gc() asks Julia to collect unneeded objects at once.
In this example, a do block writes safe to safe.txt and closes the file. A second function then reads the file in a try block, and its finally step closes the file and sets the cleaned flag.
Note
open with "w" cuts the file to empty first, so a second run prints the same words.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
A file is opened with a do block. What happens when the block ends?