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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With