+ Start a Discussion
mauro_offermannmauro_offermann 

How to share an instance variable for the entire organization?

I have a single Map that works as  custom object cache for all organization.


I can't use custom settings because this is a legacy system and all data is stored in a custom object.
I tried to declare the Map as static but all users rebuild the object in each request.

Any suggestions?

digamber.prasaddigamber.prasad

Hi,

 

Scope of static variable lasts for only one context. In next context it will be reset. If you can't use custom setting, please try using a custom object to achieve your objective.

 

Let me know if you have any specific question about this.

 

Happy to help you!

mauro_offermannmauro_offermann

This is the situation, think about a singleton pattern. I need persist in memory one FactorMap instance.

1º The first user must call getInstance method and build the map.
2º The second user should detect that FactorMap instance already exists and should not rebuild the map. But when calling getInstance should just return.

The problem is that static instance isn't persisted on differents requests contexts and the second user are rebuilding the map.

public class FactorMap {

	private static FactorMap instance;
	private Map<String, Factor__c> fm;

	private FactorMap() {
		this.fm = new Map<String, Factor__c>();
		Factor__c[] factors = [SELECT Id, Name, Foo__c, Bar__c FROM Factor__c];
		for (Factor__c factor : factors)
			this.fm.put(factor.Name, factor);
	}

	public static FactorMap getInstance() {
		if (this.instance == null)
			this.instance = new FactorMap();
		return instance;
}
}

 

digamber.prasaddigamber.prasad

Hi,

 

I got your problem. But unfortunately you cann't achieve this salesforce using static or some other apex functionality. The only available option at your disposle is CustomSetting or Custom Object.

Starz26Starz26

You could:

 

1. Create a date field for your custom setting and set it when it is built

2. In your code check that value and determin if it needs rebuilt.

3. If it meets the criteria for rebuild, rebuild and return new values

4. If it does not just return the current values.

 

 

mauro_offermannmauro_offermann

Sorry, but I think that strategy does not work for me.

1º Factor__c does not a custom setting is a custom object.
2º How I can determine if the instance was rebuilt with a date field? Compared to the current time?
3º When the user makes a second request, the static instance of the first user is lost. How could I get it back?

Thank you very much anyway.