Version française
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

Browse thread
exception safety / RAII ?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2005-03-08 (01:09)
From: Jon Harrop <jon@j...>
Subject: Re: [Caml-list] Re: exception safety / RAII ?
On Monday 07 March 2005 18:47, Michael Walter wrote:
> On Mon, 7 Mar 2005 17:29:19 +0000, Jon Harrop <> wrote:
> > Would you mind elaborating a little on what you do desire, i.e. what does
> > "using" do in C#, when would you use it and how does this relate to
> > OCaml?
> Sure. I hope the following answers all three questions at once:
> let using resource thunk =
>   try
>     let
>       result = thunk resource
>     in
>       dispose resource;
>       result
>   with
>    any_exception ->
>      dispose resource;
>      raise any_exception
> My O'Caml is not very fluent, possible "dispose resource" should read
> "resource # dispose".

Either is clear enough.

> Basically, the idea is to deterministically 
> clean up resources, as early as possible (yes, "but it's not as early
> as possible" is besides the point :-). In my experience this
> simplifies resource management and reasoning about it.

Yes, so you can use your code to do this in OCaml. My concerns with such code 
basically revolve around the possibility of incorrectly deallocating an 
external resource and then using it again. This is not possible if you rely 
on the GC but, as you say, the problem is then the lack of guarantees about 
when resources have been deallocated by what point in the code.

Perhaps explicitly asking the GC to deallocate all such resources is a better 
solution? Depending on the circumstances, this could give a big performance 
hit though...

> > Presumably this is only difficult in the more complicated case of a
> > general dependency graph between objects? In particular, one which has
> > cycles. What kinds of programs require such sophistication?
> I have no idea about with finalizers in O'Caml (hence my more
> broad/general statement), but in other languages I've worked with
> there are several limitations which all basically origin in the fact
> that finalization order in these languages was non-deterministic.

Ok, I have found that, with a little thought and careful design beforehand, 
this is not a problem in OCaml. In the case of DAG dependency graphs, my 
solution is to represent the dependency graph for the GC by maintaining a 
list of references to dependees in each object. This forces the GC to respect 
dependencies when collecting.

If the dependency graph is allowed to contain cycles then this might not work. 
I'm not sure though.

Dr Jon D Harrop, Flying Frog Consultancy Ltd.
Objective CAML for Scientists