Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will data in gen_server be kept after restarted by its supervisor?

I have a supervisor which starts many gen_server. Each gen_server has a lot of data load which takes a lot of time. I want to know when error happens, will the data stored in gen_server's state and its process dict be kept for next start so I don't need to init them again?

like image 486
Yan Avatar asked Jul 30 '11 04:07

Yan


2 Answers

The current state of an Erlang behavior is not saved anywhere. You would have to take care of that yourself.

Either you save the state regurlarly somewhere externally (in another process, in an ETS table, a database etc.) or you make sure that your init/1 function is sufficiently smart and dynamic to be able to recreate the state upon starting (recover existing files, recreate some cache based on the original input arguments etc.)

Basically, you have to define what data should survive a crash and how to persist or recreate it.

like image 54
Adam Lindberg Avatar answered Nov 13 '22 16:11

Adam Lindberg


If you have any data in your application that needs to persist a crash of your application, then you need to separate it from the application into a database (Mnesia) or ETS/DETS tables. Let the gen_server state contain live/temporary/transient info that just allows it to quickly manipulate the transient state of your application.
As soon as your gen_server init/1 is called, let it read a configuration file or Database to get a begin state. Usually, when your application depends so much on the last state of the server, each time a request comes in that manipulates the gen_server state, you extract info from it and copy it into a persistent storage (and label this data as the previous known state). This enables your init/1 function to always check for the last/previous state or whether it should begin a fresh state.

like image 41
Muzaaya Joshua Avatar answered Nov 13 '22 15:11

Muzaaya Joshua