6

When exactly is a class loaded into memory and static members are initialised?

say in below code,which statement triggers loading into memory -is it loaded only once during the execution context and is the life time same as execution context(as static varibles lifetime is execcontext) -can we programmaticaly load class by some 'load' kind of statement

public class myclass
{

    public static integer a;
    public integer b;

    public static m1()
    {
    }
}

myclass.m1();
myclass obj = new myclass();
  • The class is loaded when it is first referenced in that execution context. What would you hope to achieve with a "load" statement? – Doug B Jul 11 '13 at 10:34
  • so in the above code,myclass.m1() will trigger class loading? with a load like statement,i would hope to achieve loading a class(to intialise the static variables) without referring to class[by means of calling,static methods/object creation] – sfdc99999 Jul 11 '13 at 10:42
  • Also when is the class unloaded? – sfdc99999 Jul 11 '13 at 10:52
  • The static class only exists for the duration of your request. It's not like java where it continues to exist and is shared by other requests. – Doug B Jul 11 '13 at 11:00
6

The classes will be loaded per request and will last for the duration of that request (or a transaction).

See the documentation for Static and Instance:

Static variables are only static within the scope of the request. They’re not static across the server, or across the entire organization.

In other words, static variables are unique for each execution context and are maintained through the context.

|improve this answer|||||
  • when you say duration of your request->ie the execution context?[I dont have JAVA knowledge,so i amnt confusing it with JAVA} So if i say within same execution context,static variables can be shared--is that correct? Also does class dies early and its static members live more ?:) – sfdc – sfdc99999 Jul 11 '13 at 11:32
  • 1
    @sfdc99999 It's really hard to understand what you are saying. Within a single execution context, the static variables will be visible and can be shared, yes. Static variables will be unavailable (destroyed and garbage collected) along with the class, when the execution context ends. A static variable is available for as long the class is available, because it is defined on the class, and not on the instance of a class. It should not be possible for a static variable to outlive its class. – ipavlic Jul 11 '13 at 11:49
  • its hard to understand.Still you are giving smart answers..see :)... – sfdc99999 Jul 11 '13 at 12:13
  • Example of an execution context: Trigger fires on SObject Foo; DML done in trigger that causes another trigger to fire on Sobject Bar – cropredy Jul 13 '13 at 1:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.