14.3 Code Replacement

Erlang supports change of code in a running system. Code replacement is done on module level.

The code of a module can exist in two variants in a system: current and old. When a module is loaded into the system for the first time, the code becomes 'current'. If then a new instance of the module is loaded, the code of the previous instance becomes 'old' and the new instance becomes 'current'.

Both old and current code is valid, and can be evaluated concurrently. Fully qualified function calls always refer to current code. Old code can still be evaluated because of processes lingering in the old code.

If a third instance of the module is loaded, the code server removes (purges) the old code and any processes lingering in it is terminated. Then the third instance becomes 'current' and the previously current code becomes 'old'.

To change from old code to current code, a process must make a fully qualified function call.

Example:

  1. -module(m).
  2. -export([loop/0]).
  3.  
  4. loop() ->
  5. receive
  6. code_switch ->
  7. m:loop();
  8. Msg ->
  9. ...
  10. loop()
  11. end.

To make the process change code, send the message code_switch to it. The process then makes a fully qualified call to m:loop() and changes to current code. Notice that m:loop/0 must be exported.

For code replacement of funs to work, use the syntax fun Module:FunctionName/Arity.