Erlang: should I keep dets open and under supervision?

443 views Asked by At

I'm moving data in and out of dets and, I have a choice: I can either:

1) open dets immediately before accessing it and close it immediately after, or

%% Based on Armstrong, Programming Erlang, page 279
open() ->
   File = ?NAMEDB,
   case dets:open_file(?MODULE, [{file, File}, {keypos,2}]) of
      {ok, ?MODULE} ->
          io:format("dets opened:~p~n", [File]);
      {error,_Reason} ->
         io:format("cannot open dets table~n"),
         exit(eDetsOpen)
   end.

%% Open db, get record, close db, return name
name(Record) ->
   open(),
   #name{honorific=Honorific, fname=FName, mname=MName, lname=LName, suffix=Suffix} = Record, 
   close(),
   format_name([Honorific, FName, MName, LName, Suffix]).

2) link dets to a supervisor that re-opens it in event of a crash; e.g. access dets through gen-server with supervisor something like:

start_link() ->
   supervisor:start_link({local, ?SERVER}, ?MODULE, []).

start_child(Value, LeaseTime) ->
   supervisor:start_child(?SERVER, [Value, LeaseTime]).

init([]) ->
   Names           = {lit_names, {lit_names, start_link, []},
                     temporary, brutal_kill, worker, [zpt_gridz_scratchpad]},
   Children        = [Names],
   RestartStrategy = {simple_one_for_one, 0, 1},
                     {ok, {RestartStrategy, Children}}.

Which is best? Or is there a better choice yet?

Many thanks,

LRP

1

There are 1 answers

0
Adam Lindberg On

I think it all depends on your usage pattern. As I see it, you have a few options:

  1. Open the table, read/write some stuff, close the table. This can be used with the ram_file option for greater performance, depending on your use case.
  2. Open the table once, keep reading and writing to it as long as you need it, then close it.
  3. Open the table in one process, proxy all reads and writes through this process, then close it.

The second one is probably best in a casual use case. In fact, several processes can open the same DETS table simultaneously:

If two processes open the same table by giving the same name and arguments, then the table will have two users. If one user closes the table, it still remains open until the second user closes the table.

The third case is probably the slowest and should not be chosen unless you really have a good reason to (the data needs to be written in a certain sequence or validated atomically against other data).