function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
ssousanssousan 

How to close or destroy a class after calling it?

I have a call to a method in a class as follows:

 

String key1 ="test1";
String key2 ="test2";

long[] datalr =newlong[]{};
datalr
=TestClass.callerSub(key1,key2);
datalr
=TestClass.callerSub(key1,key2);

 

The test class is as follows:

 

publicclassTestClass{

 
privatestaticfinalLong[] P =newLong[18];



PublicTestClass{
}

publiclong[] callerSub(string key1,String key2){

long[] datalr =newlong[]{0,0};
integer i
;
system
.debug(LoggingLevel.INFO,P[0]);

datalr
[0]=2;
datalr
[1]=3;
for( i =0; i <18;++i ){
P
[i]= i+1
}
return datalr;

}
}

 

I am calling the TestClass.callerSub twice, The first time I call the debug statement:

 

system.debug(LoggingLevel.INFO,P[0]);

 

it returns null, as it should,

 

The second time I call it, the P[i] now has a value,

 

How do I close or destroy the TestClass class before I call it again?

 

Thanks

Best Answer chosen by Admin (Salesforce Developers) 
sfdcfoxsfdcfox
It is a static variable; it will exist the entire execution. Objects are automatically garbage collected when no references to the object remain. A static variable is a reference, and it will remain throughout the entire transaction, even across class calls or recursive DML statements.

Instead, you must re-initialize the static variable each time you need it cleared. In this code's case, I would make an argument that callerSub's first line of code should be p = new Long[18]; to make sure the array is re-initialized. The prior collection will automatically be reclaimed by the garbage collector.