why catch gen_server; MOD:handle_call?

Matthias Lang <>
Thu Jul 8 10:07:34 CEST 2004


Martin Logan writes:

 > The terminate function is called when a call back in a gen server fails.
 > I am wondering if this is a good idea or not.

You have a good point.

Inspired by your post, I took a quick look through the terminate
functions in a system we wrote. I found a couple of 'terminates' which
use information from the State variable to un-do side effects, even
though the State variable is no longer reliably represents those side
effects. Bad.

Moving the cleanup to a supervisor would discourage that type of
mistake, but the canned supervisors don't have any mechanism for a
process-specific cleanup. I'm not convinced they should,
either. Putting the cleanup code in the same module as the server
doesn't seem horrible, as long as you remember that you can't always
rely on the State variable being at true reflection of system state.
If you write code like this you're fine:

  terminate(normal, State) ->
        % do anything you want, the State is consistent with the world

  terminate(shutdown, State) ->
        % do anything you want, the State is consistent with the world

  terminate(Reason, Possibly_old_state) ->
        % keep in mind that the State is not necessarily consistent
        % with what has happened; the gen_server may have terminated
        % while partway through a callback.

I don't remember if they teach that in the advanced OTP course
(Francesco? Lennart?). Changing the emacs skeleton would be a
nudge in the right direction.


More information about the erlang-questions mailing list