Use a cache to save state changes to avoid opening a session for every change.
        The cache will be flushed at the end of the simulation, and when history is accessed.
965453
def flush_cache(self):
        '''
        
        '''
        logger.debug('Flushing cache {}'.format(self.db_path))
        with self.db:
            for rec in self._tups:
                self.db.execute("replace into history(agent_id, t_step, key, value) values (?, ?, ?, ?)", (rec.agent_id, rec.t_step, rec.key, rec.value))
        self._tups = list()
945424
def _save_state(self, state_file, last_pk):
        """"""
        fp = open(state_file, 'w+')
        try:
            fp.write(str(last_pk))
        finally:
            fp.close()
290638
@Override
    public void saveChanges() {
        BatchOperation saveChangeOperation = new BatchOperation(this);

        try (BatchCommand command = saveChangeOperation.createRequest()) {
            if (command == null) {
                return;
            }

            if (noTracking) {
                throw new IllegalStateException("Cannot execute saveChanges when entity tracking is disabled in session.");
            }

            _requestExecutor.execute(command, sessionInfo);
            updateSessionAfterSaveChanges(command.getResult());
            saveChangeOperation.setResult(command.getResult());
        }
    }
1240055
def save(self):
        
        self.session.add(self)
        self.session.flush()
        return self
548791
function CacheUpdate(bit, hash, state) {
  this.bit = bit;
  this.hash = hash;
  this.state = state;
}
213748
def cache(self):
        
        self.is_cached = True
        self.persist(StorageLevel.MEMORY_ONLY)
        return self
652006
def save(self, force_insert=False, force_update=False, using=None,
             update_fields=None):
        
        # Always create a new entry, instead of updating an existing model
        self.pk = None  # pylint: disable=invalid-name
        super(ConfigurationModel, self).save(
            force_insert,
            force_update,
            using,
            update_fields
        )
        cache.delete(self.cache_key_name(*[getattr(self, key) for key in self.KEY_FIELDS]))
        if self.KEY_FIELDS:
            cache.delete(self.key_values_cache_key_name())
1008663
def _use_cache(self, key, options=None):
    
    flag = ContextOptions.use_cache(options)
    if flag is None:
      flag = self._cache_policy(key)
    if flag is None:
      flag = ContextOptions.use_cache(self._conn.config)
    if flag is None:
      flag = True
    return flag
861627
def flush_cache(self, properties=None):
        
        if hasattr(self, '_cache'):
            if properties is None:
                del(self._cache)
            else:
                for prop in properties:
                    if prop in self._cache:
                        del(self._cache[prop])
535287
public void storeCache() {
        if (cacheOk && cacheRes != null && isDirty) {
            OutputStream out = null;
            try {
                out = cacheRes.putStream();
                PrintWriter writer = new PrintWriter(new OutputStreamWriter(out, "UTF-8"));
                for (SubsystemFeatureDefinitionImpl entry : cachedFeatures.values()) {
                    ImmutableAttributes imAttrs = entry.getImmutableAttributes();
                    ProvisioningDetails provDetails = entry.getProvisioningDetails();

                    if (imAttrs != null && provDetails != null) {
                        FeatureDefinitionUtils.writeAttributes(imAttrs,
                                                               provDetails,
                                                               writer);
                    } else {
                        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                            Tr.debug(tc, "Unable to write out " + entry.getFeatureName() + " to cache because the provisioning "
                                         + "detail: " + provDetails + " or imAttrs: " + imAttrs + " is null");
                        }
                    }
                }
                writer.write("@=");
                writer.write(toFeatureNameList(installedFeatures));
                writer.write(FeatureDefinitionUtils.NL);
                writer.write("-@");
                writer.write(toFeatureNameList(configuredFeatures));
                writer.write(FeatureDefinitionUtils.NL);
                writer.write("-#");
                writer.write(configurationError ? '1' : '0');
                writer.write(FeatureDefinitionUtils.NL);

                for (Map.Entry<File, BadFeature> entry : knownBadFeatures.entrySet()) {
                    writer.write("XX");
                    writeBadManifestEntry(writer, entry.getKey(), entry.getValue());
                    writer.write(FeatureDefinitionUtils.NL);
                }

                writer.flush();
                writer.close();

                isDirty = false; // mark cache as current after it has been saved
            } catch (IOException e) {
                cacheWarning(e);
            } finally {
                FeatureDefinitionUtils.tryToClose(out);
            }
        }
    }
377993
public void reset() {
	  expirationTimeFlag = UNSET;
      inactivityFlag = UNSET; 
	  idFlag = UNSET;
	  priorityFlag = UNSET;
	  sharingPolicyFlag = UNSET;
	  lock = UNSET;
	  id = null;
	  timeLimit = -1;
      inactivity = -1;
   	  expirationTime = -1;
   	  validatorExpirationTime = -1;
	  priority = -1;
	  sharingPolicy = NOT_SHARED;
	  persistToDisk = true;   
	  templates.clear();
	  template = null;
	  dataIds.clear();
	  aliasList.clear();
	  userMetaData = null;
      entryInfoPool = null;
      cacheType = CacheEntry.CACHE_TYPE_DEFAULT;
      externalCacheGroupId = null;
  }
903146
def _save_cache(self):
        """"""
        # Create the cache directory
        safe_makedirs(self.cache_dir)

        # Create/overwrite the cache file
        try:
            with open(self.cache_file, 'wb') as f:
                pickle.dump(self.data, f)
        except Exception as e:
            logger.error("Cannot write version to cache file {} ({})".format(self.cache_file, e))
30682
@Override
	protected void resetCache() {
		super.resetCache();
		cacheProperties.put(JawrConstant.SASS_GENERATOR_URL_MODE,
				useAbsoluteURL ? SASS_GENERATOR_ABSOLUTE_URL_MODE : SASS_GENERATOR_RELATIVE_URL_MODE);
	}
630452
function () {
		var updateCache = this.cache;
		for (var i = 0, n = updateCache.length; i < n; i++)
			updateCache[i].update();
	}
965552
def _saveState(self, path):
        """"""
        self.addSession()  # next session
        self._save(str(self.n_sessions), path)
260379
public void cache(String key, Object obj) {
        H.Session sess = session();
        if (null != sess) {
            sess.cache(key, obj);
        } else {
            app().cache().put(key, obj);
        }
    }
801024
@Api
	public void refresh() {
		if (state == State.INITIALIZED) { // to prevent refresh before the map is drawn
			state = State.REFRESHING;
			clear();
			ClientConfigurationService.clear(); // refresh because configuration changed, clear cache
			refreshFromConfiguration();
		}
	}