shamelessly copied from jdk8 source code for InMemoryCookieStore
975319
private boolean netscapeDomainMatches(final String domain, final String host) {
        if (domain == null || host == null) {
            return false;
        }

        // if there's no embedded dot in domain and domain is not .local
        boolean isLocalDomain = ".local".equalsIgnoreCase(domain);
        int embeddedDotInDomain = domain.indexOf('.');
        if (embeddedDotInDomain == 0) {
            embeddedDotInDomain = domain.indexOf('.', 1);
        }
        if (!isLocalDomain && (embeddedDotInDomain == -1 || embeddedDotInDomain == domain.length() - 1)) {
            return false;
        }

        // if the host name contains no dot and the domain name is .local
        int firstDotInHost = host.indexOf('.');
        if (firstDotInHost == -1 && isLocalDomain) {
            return true;
        }

        int domainLength = domain.length();
        int lengthDiff = host.length() - domainLength;
        if (lengthDiff == 0) {
            // if the host name and the domain name are just string-compare euqal
            return host.equalsIgnoreCase(domain);
        }
        else if (lengthDiff > 0) {
            // need to check H & D component
            String H = host.substring(0, lengthDiff);
            String D = host.substring(lengthDiff);

            return (D.equalsIgnoreCase(domain));
        }
        else if (lengthDiff == -1) {
            // if domain is actually .host
            return (domain.charAt(0) == '.' &&
                    host.equalsIgnoreCase(domain.substring(1)));
        }

        return false;
    }
980304
public static JVMMemoryInfo getJVMMemoryInfo() {
        Runtime runtime = Runtime.getRuntime();
        double freeMemory = (double) runtime.freeMemory() / (1024 * 1024);
        double maxMemory = (double) runtime.maxMemory() / (1024 * 1024);
        double totalMemory = (double) runtime.totalMemory() / (1024 * 1024);
        return new JVMMemoryInfo(freeMemory, maxMemory, totalMemory);
    }
618187
@Override
    public String getCacheDigest(String cacheInstance, boolean useMemoryCacheDigest,
                                 boolean cacheIDOnly, boolean debug) throws javax.management.AttributeNotFoundException { // LI4337-17

        if (tc.isEntryEnabled()) {
            Tr.entry(tc, "getCacheDigest: cacheInstance=" + cacheInstance + " useMemoryCacheDigest=" + useMemoryCacheDigest +
                         " cacheIDOnly=" + cacheIDOnly + " debug=" + debug);
        }
        // Get the cache for this cacheInstance
        DCache cache1 = getCache(cacheInstance);

        // Get the message digest
        getMessageDigestMD5();

        // Calculate total hashcode for cache ids and cache value in memory cache  
        int totalHashcode = cache1.getMemoryCacheHashcode(debug, !cacheIDOnly);

        if (cacheIDOnly == true) {
            // Calculate total hashcode for cache ids in PushPullTable  
            totalHashcode += cache1.getCacheIdsHashcodeInPushPullTable(debug);
        }

        if (useMemoryCacheDigest == false) {
            // Calculate total hashcode for cache ids and cache value in disk cache  
            try {
                totalHashcode += cache1.getDiskCacheHashcode(debug, !cacheIDOnly);
            } catch (DynamicCacheException e) {
                Tr.error(tc, "DYNA1053E", new Object[] { DynaCacheConstants.MBEAN_GET_CACHE_DIGEST, e.getMessage() });
                throw new AttributeNotFoundException(e.getMessage());
            }
        }

        // Convert hashcode to MD5 digest
        String md5Hash = MessageDigestUtility.processMessageDigestForData(MBeans.messageDigestMD5, totalHashcode);

        if (tc.isEntryEnabled()) {
            Tr.exit(tc, "getCacheDigest: Exiting. Entire cache hash in MD5 is " + md5Hash + " for cacheInstance = " + cacheInstance);
        }
        return md5Hash;
    }
1088444
static void checkDirectMemCapacity(final int k, final long n, final long memCapBytes) {
    final int reqBufBytes = getCompactStorageBytes(k, n);

    if (memCapBytes < reqBufBytes) {
      throw new SketchesArgumentException("Possible corruption: Memory capacity too small: "
          + memCapBytes + " < " + reqBufBytes);
    }
  }
1084857
function createMemoryHistory(props = {}) {
  const {
    getUserConfirmation,
    initialEntries = ['/'],
    initialIndex = 0,
    keyLength = 6
  } = props;

  const transitionManager = createTransitionManager();

  function setState(nextState) {
    Object.assign(history, nextState);
    history.length = history.entries.length;
    transitionManager.notifyListeners(history.location, history.action);
  }

  function createKey() {
    return Math.random()
      .toString(36)
      .substr(2, keyLength);
  }

  const index = clamp(initialIndex, 0, initialEntries.length - 1);
  const entries = initialEntries.map(
    entry =>
      typeof entry === 'string'
        ? createLocation(entry, undefined, createKey())
        : createLocation(entry, undefined, entry.key || createKey())
  );

  // Public interface

  const createHref = createPath;

  function push(path, state) {
    warning(
      !(
        typeof path === 'object' &&
        path.state !== undefined &&
        state !== undefined
      ),
      'You should avoid providing a 2nd state argument to push when the 1st ' +
        'argument is a location-like object that already has state; it is ignored'
    );

    const action = 'PUSH';
    const location = createLocation(path, state, createKey(), history.location);

    transitionManager.confirmTransitionTo(
      location,
      action,
      getUserConfirmation,
      ok => {
        if (!ok) return;

        const prevIndex = history.index;
        const nextIndex = prevIndex + 1;

        const nextEntries = history.entries.slice(0);
        if (nextEntries.length > nextIndex) {
          nextEntries.splice(
            nextIndex,
            nextEntries.length - nextIndex,
            location
          );
        } else {
          nextEntries.push(location);
        }

        setState({
          action,
          location,
          index: nextIndex,
          entries: nextEntries
        });
      }
    );
  }

  function replace(path, state) {
    warning(
      !(
        typeof path === 'object' &&
        path.state !== undefined &&
        state !== undefined
      ),
      'You should avoid providing a 2nd state argument to replace when the 1st ' +
        'argument is a location-like object that already has state; it is ignored'
    );

    const action = 'REPLACE';
    const location = createLocation(path, state, createKey(), history.location);

    transitionManager.confirmTransitionTo(
      location,
      action,
      getUserConfirmation,
      ok => {
        if (!ok) return;

        history.entries[history.index] = location;

        setState({ action, location });
      }
    );
  }

  function go(n) {
    const nextIndex = clamp(history.index + n, 0, history.entries.length - 1);

    const action = 'POP';
    const location = history.entries[nextIndex];

    transitionManager.confirmTransitionTo(
      location,
      action,
      getUserConfirmation,
      ok => {
        if (ok) {
          setState({
            action,
            location,
            index: nextIndex
          });
        } else {
          // Mimic the behavior of DOM histories by
          // causing a render after a cancelled POP.
          setState();
        }
      }
    );
  }

  function goBack() {
    go(-1);
  }

  function goForward() {
    go(1);
  }

  function canGo(n) {
    const nextIndex = history.index + n;
    return nextIndex >= 0 && nextIndex < history.entries.length;
  }

  function block(prompt = false) {
    return transitionManager.setPrompt(prompt);
  }

  function listen(listener) {
    return transitionManager.appendListener(listener);
  }

  const history = {
    length: entries.length,
    action: 'POP',
    location: entries[index],
    index,
    entries,
    createHref,
    push,
    replace,
    go,
    goBack,
    goForward,
    canGo,
    block,
    listen
  };

  return history;
}
387952
@Override
  public V computeIfAbsent(final K key, final Callable<V> callable) {
    Entry<K,V> e;
    for (;;) {
      e = lookupOrNewEntry(key);
      if (e.hasFreshData(clock)) {
        return returnValue(e);
      }
      synchronized (e) {
        e.waitForProcessing();
        if (e.hasFreshData(clock)) {
          return returnValue(e);
        }
        if (e.isGone()) {
          metrics.goneSpin();
          continue;
        }
        e.startProcessing(Entry.ProcessingState.COMPUTE);
        break;
      }
    }
    metrics.peekMiss();
    boolean _finished = false;
    long t = 0, t0 = 0;
    V _value;
    try {
      if (!isUpdateTimeNeeded()) {
        _value = callable.call();
      } else {
        t0 = clock.millis();
        _value = callable.call();
        if (!metrics.isDisabled()) {
          t = clock.millis();
        }
      }
      synchronized (e) {
        insertOrUpdateAndCalculateExpiry(e, _value, t0, t, t0, INSERT_STAT_PUT);
        e.processingDone();
      }
      _finished = true;

    } catch (RuntimeException ex) {
      throw ex;
    } catch (Exception ex) {
      throw new CacheLoaderException(ex);
    } finally {
      e.ensureAbort(_finished);
    }
    return returnValue(e);
  }
641519
function memoryAppender(layout, timezoneOffset) {
        layout = layout || layouts.basicLayout;
        return function(loggingEvent) {
            if((buffer.length + 1) > maxBufferSize)
            {
                var numtoRemove = (buffer.length - maxBufferSize) + 1;
                if(numtoRemove > 0){ buffer.splice(0, numtoRemove); }
            }
            buffer.push(layout(loggingEvent, timezoneOffset));
        };
    }
591836
private boolean enlargeMemory() throws InterruptedException {
        int bytesAllocated = DynamicMemoryAllocater.INSTANCES[gp.instanceID].allocateNextChunk();
        if (bytesAllocated > 0) {

            byte[] mem = new byte[bytesAllocated];
            byte[][] new_mem = new byte[memory.length + 1][];
            for (int i = 0; i < memory.length; i++) {
                new_mem[i] = memory[i];
            }
            lastChunkIndex++;
            new_mem[lastChunkIndex] = mem;
            memory = new_mem;
            position_in_chunk = 0;
            return true;
        } else {
            return false;
        }
    }
418030
protected void saveRememberMeKeyToCookie(USER_ENTITY userEntity, USER_BEAN userBean) {
        final int expireDays = getRememberMeAccessTokenExpireDays();
        getCookieRememberMeKey().ifPresent(cookieKey -> {
            doSaveRememberMeCookie(userEntity, userBean, expireDays, cookieKey);
        });
    }
882306
@Override
    protected void putDumpInfoTo(Map<String, Object> result) {
        if(this.cookieMap.size() > 0) {
            result.put(DumpConstants.COOKIES, cookieMap);
        }
    }
1142672
public long cleanUpAllAllocatedMemory() {
    synchronized (this) {
      for (MemoryConsumer c: consumers) {
        if (c != null && c.getUsed() > 0) {
          // In case of failed task, it's normal to see leaked memory
          logger.debug("unreleased " + Utils.bytesToString(c.getUsed()) + " memory from " + c);
        }
      }
      consumers.clear();

      for (MemoryBlock page : pageTable) {
        if (page != null) {
          logger.debug("unreleased page: " + page + " in task " + taskAttemptId);
          page.pageNumber = MemoryBlock.FREED_IN_TMM_PAGE_NUMBER;
          memoryManager.tungstenMemoryAllocator().free(page);
        }
      }
      Arrays.fill(pageTable, null);
    }

    // release the memory that is not used by any consumer (acquired for pages in tungsten mode).
    memoryManager.releaseExecutionMemory(acquiredButNotUsed, taskAttemptId, tungstenMemoryMode);

    return memoryManager.releaseAllExecutionMemoryForTask(taskAttemptId);
  }
843300
public byte[] methodCallRewriteUseCacheIfAvailable(String slashedClassName, byte[] bytes) {
		if (GlobalConfiguration.isCaching) {
			return MethodInvokerRewriter.rewriteUsingCache(slashedClassName, this, bytes);
		}
		else {
			return MethodInvokerRewriter.rewrite(this, bytes);
		}
	}
732541
@Override
    public Serializable generateKey(final MethodInvocation methodInvocation) {
        //Determine the tareted CachableMethod
        final CachableMethod cachableMethod = this.resolveCacheableMethod(methodInvocation);

        //Use the resolved cachableMethod to determine the seed Map and then get the hash of the key elements
        final Object[] methodArguments = methodInvocation.getArguments();
        final Map<String, Object> seed = this.getSeed(methodArguments, cachableMethod);
        final Integer keyHashCode = this.getKeyHash(seed);

        //If no code generated return null
        if (keyHashCode == null) {
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("No cache key generated for MethodInvocation='" + methodInvocation + "'");
            }
            return null;
        }

        //Calculate the hashCode and checkSum
        final HashCodeCalculator hashCodeCalculator = new HashCodeCalculator();
        hashCodeCalculator.append(keyHashCode);

        //Assemble the serializable key object
        final long checkSum = hashCodeCalculator.getCheckSum();
        final int hashCode = hashCodeCalculator.getHashCode();
        final HashCodeCacheKey hashCodeCacheKey = new HashCodeCacheKey(checkSum, hashCode);

        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Generated cache key '" + hashCodeCacheKey + "' for MethodInvocation='" + methodInvocation + "'");
        }
        return hashCodeCacheKey;
    }
990047
private void logOutOfMemoryError()
  {
    logger.error("Dump some crucial information below:\n" +
                 "Total milliseconds waiting for chunks: {},\n" +
                 "Total memory used: {}, Max heap size: {}, total download time: {} millisec,\n" +
                 "total parsing time: {} milliseconds, total chunks: {},\n" +
                 "currentMemoryUsage in Byte: {}, currentMemoryLimit in Bytes: {} \n" +
                 "nextChunkToDownload: {}, nextChunkToConsume: {}\n" +
                 "Several suggestions to try to resolve the OOM issue:\n" +
                 "1. increase the JVM heap size if you have more space; or \n" +
                 "2. use CLIENT_MEMORY_LIMIT to reduce the memory usage by the JDBC driver " +
                 "(https://docs.snowflake.net/manuals/sql-reference/parameters.html#client-memory-limit)" +
                 "3. please make sure 2 * CLIENT_PREFETCH_THREADS * CLIENT_RESULT_CHUNK_SIZE < CLIENT_MEMORY_LIMIT. " +
                 "If not, please reduce CLIENT_PREFETCH_THREADS and CLIENT_RESULT_CHUNK_SIZE too.",
                 numberMillisWaitingForChunks,
                 Runtime.getRuntime().totalMemory(), Runtime.getRuntime().maxMemory(),
                 totalMillisDownloadingChunks.get(),
                 totalMillisParsingChunks.get(), chunks.size(), currentMemoryUsage, memoryLimit,
                 nextChunkToDownload, nextChunkToConsume);
  }
862014
def free_memory(cls, exclude=None):
        """"""

        annotations_in_memory = Annotation.__ANNOTATIONS_IN_MEMORY__

        exclude = () if exclude is None else exclude

        for annotation_cls in list(annotations_in_memory.keys()):

            if issubclass(annotation_cls, exclude):
                continue

            if issubclass(annotation_cls, cls):
                del annotations_in_memory[annotation_cls]
369828
private Snapshot createMemorySnapshot(SnapshotDescriptor descriptor) {
    HeapBuffer buffer = HeapBuffer.allocate(SnapshotDescriptor.BYTES, Integer.MAX_VALUE);
    Snapshot snapshot = new MemorySnapshot(buffer, descriptor.copyTo(buffer), this);
    LOGGER.debug("Created memory snapshot: {}", snapshot);
    return snapshot;
  }
639268
public void updateMemoryInfo() {

		MemoryMXBean meminfo = ManagementFactory.getMemoryMXBean();

		MemoryUsage usage = meminfo.getHeapMemoryUsage();
		long _heapUsed = usage.getUsed();
		updateMaximum(heapUsed, _heapUsed);
		updateMaximum(heapTotal, usage.getMax());

		usage = meminfo.getNonHeapMemoryUsage();
		updateMaximum(nonHeapUsed, usage.getUsed());
		updateMaximum(nonHeapTotal, usage.getMax());

		// Log the memory usage if requested. Check the log level before logging
		// to minimize object creation overheads during preparation of the call
		// parameters.
		if (memoryLogger.isLoggable(Level.INFO)) {
			memoryLogger.log(Level.INFO, "MEM", new Object[] { _heapUsed });
		}
	}