How to manage memory when using JuMP+Gurobi?

At the moment it is illegal to call GRBfreeenv on an environment because GRBfreeenv is called as part of the finaliser.

One option is:

julia> import Gurobi

julia> env = Gurobi.Env();
Set parameter WLSAccessID
Set parameter WLSSecret
Set parameter LicenseID to value 722777
WLS license 722777 - registered to JuMP Development

julia> finalize(env)

julia> env
Gurobi.Env(Ptr{Nothing}(0x0000000000000000), true, 0)

julia> exit()

I have been thinking to add the syntax:

Gurobi.Env() do env
    # use the env
end

which would explicitly scope when the environment is created and destroyed.

Edit: I remember why I didn’t do this before. Consider the situation:

using Gurobi
Gurobi.Env() do env
    model_1 = Gurobi.Optimizer(env)
    # Stuff
    model_2 = Gurobi.Optimizer(env)
    # Stuff
    return
end

Before we can run the finaliser for env we must first have finalised all the referenced models. If the function runs, we finalise env, and then sometime later the GC finalises model_1 Gurobi crashes.