detect gabarge collector occurance. Require v8 for now, so chrome or node.js.
typical usage: <code>new GcMonitor().start();</code>

@class monitor gabage collector activities

see details in http://buildnewgames.com/garbage-collector-friendly-code/
767112
function(){
	// init a timer
	var _this	= this;
	var timerid	= null;
	// define function to return used heap size
	var inNode	= typeof(window) === 'undefined' ? true : false;
	var usedHeapSize= inNode ? function(){
		return process.memoryUsage().heapUsed;	
	} : function(){
		if( !window.performance || !window.performance.memory )	return 0;
		return window.performance.memory.usedJSHeapSize;	
	};

	// sanity check - if not available, output a warning
	if( GcMonitor.isAvailable() === false ){
		// open -a "/Applications/Google Chrome.app" --args --enable-memory-info
		console.warn('memory info are unavailable... for chrome, use --enable-memory-info. Other browsers dont have this feature.')
	}

	/**
	 * Start monitoring periodically
	 * 
	 * @param {Function|undefined} onChange optional function to notify when gc occurs
	 * @param {Number|undefined} period period of the check. default to 50ms
	 */
	this.start	= function(onChange, period){
		period	= period	|| 1000/60;
		onChange= onChange	|| function(delta){
			function bytesToSize(bytes, nFractDigit) {
				var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
				if (bytes == 0) return '0';
				nFractDigit	= nFractDigit !== undefined ? nFractDigit : 2;
				var precision	= Math.pow(10, nFractDigit);
				var i 		= Math.floor(Math.log(bytes) / Math.log(1024));
				return Math.round(bytes*precision / Math.pow(1024, i))/precision + ' ' + sizes[i];
			};
			console.warn(new Date + " -- GC occured! saved", bytesToSize(delta), 'consuming at', bytesToSize(burnRate), 'per second')
		}
		timerid	= setInterval(function(){
			_this.check(onChange);
		}, period);
		return this;	// for chained api
	};
	/**
	 * Stop monitoring periodically
	 */
	this.stop	= function(){
		cancelInterval(timerid);	
	};
	
	var lastUsedHeap	= null;
	var lastTimestamp	= null;
	var burnRate		= null;	
	/**
	 * Check if currently used memory is less than previous check. If so it 
	 * is assume a GC occured
	 * 
	 * @param  {Function|undefined} onChange callback notified synchronously if gc occured
	 */
	this.check	= function(onChange){
		// parameter polymorphism
		onChange	= onChange || function(property){}

		var present	= Date.now();//console.log('present', (present - lastTimestamp)/1000)
		var currUsedSize= usedHeapSize();

		if( lastUsedHeap === null ){
			lastUsedHeap	= currUsedSize;
			lastTimestamp	= present;
			return;
		}

		// check if the heap size in this cycle is LESS than what we had last
		// cycle; if so, then the garbage collector has kicked in
		var deltaMem	= currUsedSize - lastUsedHeap;
		if( deltaMem < 0 ){
			onChange(-deltaMem, burnRate);		
		}else{
			var deltaTime	= present - lastTimestamp
			var newBurnrate	= deltaMem / (deltaTime/1000);
			if( burnRate === null )	burnRate	= newBurnrate;
			var friction	= 0.99;
			burnRate	= burnRate * friction + newBurnrate * (1-friction);
		}

		lastUsedHeap	= currUsedSize;
		lastTimestamp	= present;
	}
	
	/**
	 * getter for the burnRate
	 * @type {Number}
	 */
	this.burnRate	= function(){
		if( burnRate === null )	return 0;
		return burnRate;
	}
	
	/**
	 * getter for the usedHeapSize
	 * @return {Number} used heap size in byte
	 */
	this.usedHeapSize	= function(){
		return usedHeapSize();
	}
}
403515
private static void tryWaitingForGC() {
    // We could try to preallocate memory mx bean and count collections...
    // there is no guarantee it doesn't allocate stuff too though.
    final long timeout = System.currentTimeMillis() + 2000;
    while (System.currentTimeMillis() < timeout) {
      System.gc(); 
      try {
        Thread.sleep(250);
      } catch (InterruptedException e) {
        break;
      }
    }
  }
255836
static void logCurrentThreadTrace() {
    ThreadTrace trace = getThreadTrace();

    // New threads must call Tracer.initCurrentThreadTrace() before Tracer
    // statistics are gathered. This is a recent change (Jun 2007) that
    // prevents spurious Third Eye messages when an application uses a class in
    // a different package that happens to call Tracer without knowledge of the
    // application authors.
    if (!trace.isInitialized()) {
      logger.log(
          Level.INFO,
          "Tracer log requested for this thread but was not "
              + "initialized using Tracer.initCurrentThreadTrace().",
          new Throwable());
      return;
    }

    if (!trace.isEmpty()) {
      logger.log(Level.INFO, "timers:\n{0}", getCurrentThreadTraceReport());
    }
  }
1354933
@SuppressWarnings("InfiniteLoopStatement")
	public static void main(String[] args) throws Exception {
		SimonManager.callback().addCallback(new JmxRegisterCallback("org.javasimon.examples.jmx.JmxCallbackExample"));

		Counter counter = SimonManager.getCounter("org.javasimon.examples.jmx.counter");
		Stopwatch stopwatch = SimonManager.getStopwatch("org.javasimon.examples.jmx.stopwatch");
		// these created just to have more stuff in jconsole
		SimonManager.getCounter("org.javasimon.different.counter");
		SimonManager.getStopwatch("org.javasimon.some.other.jmx.stopwatch1");
		SimonManager.getStopwatch("org.javasimon.some.other.jmx.stopwatch2");
		System.out.println("Now open jconsole and check it out...\nWatch org.javasimon.examples.jmx.stopwatch for changes.");
		while (true) {
			counter.increase();
			try (Split ignored = stopwatch.start()) {
				ExampleUtils.waitRandomlySquared(40);
			}
		}
	}
1223555
public function collectGarbage()
    {

        // we need the bean manager that handles all the beans
        /** @var \AppserverIo\Psr\EnterpriseBeans\BeanContextInterface $beanManager */
        $beanManager = $this->getApplication()->search(BeanContextInterface::IDENTIFIER);

        // load the map with the startup bean tasks
        /** @var \AppserverIo\Storage\GenericStackable $statefulSessionBeans */
        $startupBeanTasks = $beanManager->getStartupBeanTasks();

        // write a log message with size of startup bean tasks to be garbage collected
        $this->log(LogLevel::DEBUG, sprintf('Found "%d" startup been tasks to be garbage collected', sizeof($startupBeanTasks)));

        // iterate over the applications sessions with stateful session beans
        /** @var \Thread $startupBeanTask */
        foreach ($startupBeanTasks as $identifier => $startupBeanTask) {
            // check the lifetime of the stateful session beans
            if ($startupBeanTask->isRunning()) {
                // write a log message
                $this->log(LogLevel::DEBUG, sprintf('Startup bean task "%s" is still running', $identifier));
            } else {
                // remove the startup been task if it has been finished
                unset($startupBeanTasks[$identifier]);
                // write a log message
                $this->log(LogLevel::DEBUG, sprintf('Successfully removed startup bean task "%s"', $identifier));
                // reduce CPU load
                usleep(1000);
            }
        }

        // profile the size of the sessions
        /** @var \Psr\Log\LoggerInterface $this->profileLogger */
        if ($this->profileLogger) {
            $this->profileLogger->debug(
                sprintf('Processed startup been task garbage collector, handling "%d" startup bean tasks', sizeof($startupBeanTasks))
            );
        }
    }
842530
private Counter initAndRegisterCounter(String name) {
        BasicCounter counter = new BasicCounter(MonitorConfig.builder(name).build());
        DefaultMonitorRegistry.getInstance().register(counter);
        return counter;
    }
1186914
protected void forceStartOpenOfficeJurtCleanup(ClassLoaderLeakPreventor preventor) {
    if(stopThreads) {
      if(preventor.isLoadedByClassLoader(preventor.findClass(JURT_ASYNCHRONOUS_FINALIZER))) {
        /* 
          The com.sun.star.lib.util.AsynchronousFinalizer class was found and loaded, which means that in case the
          static block that starts the daemon thread had not been started yet, it has been started now.
          
          Now let's force Garbage Collection, with the hopes of having the finalize()ers that put Jobs on the
          AsynchronousFinalizer queue be executed. Then just leave it, and handle the rest in {@link #stopThreads}.
          */
        preventor.info("OpenOffice JURT AsynchronousFinalizer thread started - forcing garbage collection to invoke finalizers");
        ClassLoaderLeakPreventor.gc();
      }
    }
    else {
      // Check for class existence without loading class and thus executing static block
      if(preventor.getClassLoader().getResource("com/sun/star/lib/util/AsynchronousFinalizer.class") != null) {
        preventor.warn("OpenOffice JURT AsynchronousFinalizer thread will not be stopped if started, as stopThreads is false");
        /* 
         By forcing Garbage Collection, we'll hopefully start the thread now, in case it would have been started by
         GC later, so that at least it will appear in the logs. 
         */
        ClassLoaderLeakPreventor.gc();
      }
    }
  }
795975
private synchronized void startWeakRefCleaner() {
        weakRefCleaner = new Thread(() -> {
            boolean running = true;
            while (running) {
                try {
                    // just wait, no need to get the - gc'ed object
                    weakReferenceQueue.remove();

                    // clean up the coordinateLines entries
                    final Set<String> coordinateLinesToRemove = new HashSet<>();
                    synchronized (coordinateLines) {
                        coordinateLines.forEach((k, v) -> {
                            if (null == v.get()) {
                                coordinateLinesToRemove.add(k);
                                if (logger.isTraceEnabled()) {
                                    logger.trace("need to cleanup gc'ed coordinate line {}", k);
                                }
                            }
                        });
                    }
                    // run on the JavaFX thread, as removeCoordinateLineWithId() calls methods from the WebView
                    Platform.runLater(() -> coordinateLinesToRemove.forEach(this::removeCoordinateLineWithId));

                    // clean up the MapCoordinateElement entries
                    final Set<String> mapCoordinateElementsToRemove = new HashSet<>();
                    synchronized (mapCoordinateElements) {
                        mapCoordinateElements.forEach((k, v) -> {
                            if (null == v.get()) {
                                mapCoordinateElementsToRemove.add(k);
                                if (logger.isTraceEnabled()) {
                                    logger.trace("need to cleanup gc'ed element {}", k);
                                }
                            }
                        });
                    }
                    // run on the JavaFX thread, as removeCoordinateLineWithId() calls methods from the WebView
                    Platform.runLater(
                            () -> mapCoordinateElementsToRemove.forEach(this::removeMapCoordinateElementWithId));
                } catch (InterruptedException e) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("thread interrupted");
                    }
                    running = false;
                }
            }
        });
        weakRefCleaner.setName("MapView-WeakRef-Cleaner");
        weakRefCleaner.setDaemon(true);
        weakRefCleaner.start();
    }
1149084
function (successCallback, errorCallback, deviceHandle, charHandle) {

			winble.logger.logDebug("enableCharacteristicNotification", "deviceHandle='" + deviceHandle + ", charHandle='" + charHandle + "'");

			// Find the requested device in our list of discovered devices
			var device = winble.deviceManager.getDeviceFromHandle(deviceHandle, "enableCharacteristicNotification", errorCallback);
			if (device == null)
				return;

			// Find the requested characteristic in the device's list of characteristics
			var characteristic = winble.deviceManager.getCharacteristicFromHandle(device, charHandle, "enableCharacteristicNotification", errorCallback);
			if (characteristic == null)
				return;

			// Make sure this characteristic supports sending of notifications, notify caller if not.
			if (!(characteristic.gattChar.characteristicProperties & winble.gatt.GattCharacteristicProperties.notify)) {
				var msg = "This characteristic does not support notifications";
				winble.logger.logDebug("enableCharacteristicNotification", msg);
				errorCallback(msg);
				return;
			}

			// Create callback to handle notifications; here we will get the new value into a UTF8 buffer and send it to the caller
			characteristic.onValueChanged = function (args) {
				winble.logger.logDebug("enableCharacteristicNotification", "** Windows called our callback! **");
				var data = Uint8Array(args.characteristicValue.length);
				Windows.Storage.Streams.DataReader.fromBuffer(args.characteristicValue).readBytes(data);
				successCallback(data, { keepCallback: true });
			};

			// Register the callback
			try {
				characteristic.gattChar.addEventListener("valuechanged", characteristic.onValueChanged, false);
			} catch (e) {
				var msg = "Could not add event listener:" + e;
				winble.logger.logError("enableCharacteristicNotification", msg);
				errorCallback(msg);
				return;
			}

			// Tell the characteristic to start sending us notifications.
			// In order to avoid unnecessary communication with the device, first determine if the device is already
			// correctly configured to send notifications. By default ReadClientCharacteristicConfigurationDescriptorAsync
			// will attempt to get the current value from the system cache, so physical communication with the device
			// is not typically required.
			characteristic.gattChar.readClientCharacteristicConfigurationDescriptorAsync().then(
				function (currentDescriptorValue) {

					// No need to configure characteristic to send notifications if it's already configured
					if ((currentDescriptorValue.status !== winble.gatt.GattCommunicationStatus.success) ||
					(currentDescriptorValue.clientCharacteristicConfigurationDescriptor !==
						winble.gatt.GattClientCharacteristicConfigurationDescriptorValue.notify)) {

						// Set the Client Characteristic Configuration Descriptor to enable the device to send
						// notifications when the Characteristic value changes.
						winble.logger.logDebug("enableCharacteristicNotification", "Configuring characteristic for notifications");
						characteristic.gattChar.writeClientCharacteristicConfigurationDescriptorAsync(
							winble.gatt.GattClientCharacteristicConfigurationDescriptorValue.notify).then(
							function (commStatus) {
								if (commStatus == winble.gatt.GattCommunicationStatus.success) {
									winble.logger.logDebug("enableCharacteristicNotification", "gattChar.writeClientCharacteristicConfigurationDescriptorAsync completed with success");
								} else {
									var msg = "Could not configure characteristic for notifications, device unreachable. GattCommunicationStatus = " + commStatus;
									winble.logger.logError("enableCharacteristicNotification", "enableCharacteristicNotification", msg);
									errorCallback(msg);
								}
							});
					} else {
						winble.logger.logDebug("enableCharacteristicNotification", "Characteristic is already configured for notifications");
					}
				});
		}
836966
function _gpfEventsTriggerHandler (event, eventsHandler, resolvePromise) {
    var eventHandler = _getEventHandler(event, eventsHandler);
    eventHandler(event);
    if (undefined !== resolvePromise) {
        resolvePromise(event);
    }
}
472348
public static void main(String argv[]) throws Exception {
    StringUtils.startupShutdownMessage(UtilizationCollector.class, argv, LOG);
    try {
      Configuration conf = new Configuration();
      UtilizationCollector collector = new UtilizationCollector(conf);
      if (collector != null) {
        collector.join();
      }
    } catch (Throwable e) {
      LOG.error(StringUtils.stringifyException(e));
      System.exit(-1);
    }
  }
1271614
function _gpfAllocateEventDispatcherListeners (object) {
    var listeners = object._eventDispatcherListeners;
    if (!listeners) {
        listeners = object._eventDispatcherListeners = {};
    }
    return listeners;
}
822176
function createAggregator(setter, initializer) {
  return function(collection, iteratee) {
    var func = isArray_1(collection) ? _arrayAggregator : _baseAggregator,
        accumulator = initializer ? initializer() : {};

    return func(collection, setter, _baseIteratee(iteratee, 2), accumulator);
  };
}
101476
public void notifyStart() {
        try {
            eventSource.onApplicationAvailableForService(new ApplicationEvent(this, this, new com.ibm.ws.webcontainer.util.IteratorEnumerator(config.getServletNames())));
            // LIBERTY: next line added by V8 sync
            //this.setInitialized(true);
        } catch (Exception e) {
            com.ibm.wsspi.webcontainer.util.FFDCWrapper.processException(e, CLASS_NAME + ".started", "3220", this);
            // pk435011
            logger.logp(Level.SEVERE, CLASS_NAME, "started", "error.on.collaborator.started.call");
        }
    }
242896
public synchronized void gc() {
        if (!configuration.isUseGc()) {
            LOG.trace("GC deactivated, no beans will be removed!");
            return;
        }

        LOG.trace("Garbage collection started! GC will remove {} beans!", removeOnGC.size());

        onRemoveCallback.onReject(removeOnGC.keySet());

        for (Map.Entry<Instance, Object> entry : removeOnGC.entrySet()) {
            Instance removedInstance = entry.getKey();
            for (Property property : removedInstance.getProperties()) {
                propertyToParent.remove(property);
            }
            for (ObservableList list : removedInstance.getLists()) {
                listToParent.remove(list);
            }
            allInstances.remove(entry.getValue());
        }

        removedBeansCount = removedBeansCount + removeOnGC.size();
        removeOnGC.clear();
        gcCalls = gcCalls + 1;

        LOG.trace("Garbage collection done! GC currently manages {} referenced beans!", allInstances.size());
    }
992748
function Collector(expected) {
  this.expectKeys = Array.isArray(expected) ? new Set(expected) : null;
  this.expected = this.expectKeys ? expected.length : expected;
  this.keys = new Set();
  this.count = 0;
  this.timer = null;
  this.onDone = common.emptiness;
  this.isDistinct = false;
  this.isDone = false;
  this.data = {};
}
1330264
function() {
		
		var self = this;
		
		// in case the selfDestruction option has been changed by a method call
		if (self.__options.selfDestruction) {
			
			// the GC task
			self.__garbageCollector = setInterval(function() {
				
				var now = new Date().getTime();
				
				// forget the old events
				self.__touchEvents = $.grep(self.__touchEvents, function(event, i) {
					// 1 minute
					return now - event.time > 60000;
				});
				
				// auto-destruct if the origin is gone
				if (!bodyContains(self._$origin)) {
					
					self.close(function(){
						self.destroy();
					});
				}
			}, 20000);
		}
		else {
			clearInterval(self.__garbageCollector);
		}
		
		return self;
	}