2 Minutes To Code (β Version)

Simon - 2 minute tutorial

Thread-safe profiling : How to profile in multi-threaded scenario

The Simon apis are thread-safe i.e. multiple threads can record events with stopwatch simultaneously.

However, when reading different statistics from Stopwatch directly while other threads are still recording events with it, will give slightly incorrect data.

To solve this, Simon provides a org.javasimon.StopwatchSample object through the method sample() of Stopwatch object which will take a snapshot of statistics in Stopwatch at a particular point of time and then expose these data with the same set of apis as provided by Stopwatch object.

There is another api sampleAndReset() of Stopwatch object which will take a snapshot and then reset all fields of the stopwatch to zero for getting data afresh.
package com.techfundaes.simonBag;

import java.util.ArrayList;

import org.javasimon.SimonManager;
import org.javasimon.Stopwatch;
import org.javasimon.StopwatchSample;

public class SimonUseThreadSafe
{
	static ArrayList workerThreadList = new ArrayList();
	
	public static void main(String[] args) throws Exception
	{
		createWorkerThreads();
		
		Stopwatch stopwatch = SimonManager.getStopwatch("use.multiThreaded");
		StopwatchSample stopwatchSample = stopwatch.sample();
		for(int i = 0; i < 5; i++)
		{ 
			stopwatchSample = stopwatch.sample();
			
			System.out.println(stopwatchSample.getCounter());
			System.out.println(stopwatchSample.getMax()/1024/1024);
			System.out.println(stopwatchSample.getMin()/1024/1024);
			System.out.printf("%.2f%n", stopwatchSample.getMean()/1024/1024);
			System.out.println(stopwatchSample.getTotal()/1024/1024);
			Thread.sleep(100);
		}
	}

	private static void createWorkerThreads()
	{
		for (int i = 0; i < 5; i++)
		{
			WorkerThread workerThread = new WorkerThread();
			workerThreadList.add(workerThread);
			workerThread.start();
		}	
	}
	
	private static void joinWorkerThreads()
	{
		for (int i = 0; i < workerThreadList.size(); i++)
		{
			try
			{
				workerThreadList.get(i).join();
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
		}
	}


}