Memcached Stats

The following is the list of all names sent in
response to the "stats" command, together with the type of the value
sent for this name, and the meaning of the value.

In the type column below, "32u" means a 32-bit unsigned integer, "64u"
means a 64-bit unsigner integer. '32u:32u' means two 32-but unsigned
integers separated by a colon.

Name              Type     Meaning
pid               32u      Process id of this server process
uptime            32u      Number of seconds this server has been running
time              32u      current UNIX time according to the server
version           string   Version string of this server
pointer_size      32       Default size of pointers on the host OS
                           (generally 32 or 64)
rusage_user       32u:32u  Accumulated user time for this process 
rusage_system     32u:32u  Accumulated system time for this process 
curr_items        32u      Current number of items stored by the server
total_items       32u      Total number of items stored by this server 
                           ever since it started
bytes             64u      Current number of bytes used by this server 
                           to store items
curr_connections  32u      Number of open connections
total_connections 32u      Total number of connections opened since 
                           the server started running
connection_structures 32u  Number of connection structures allocated 
                           by the server
cmd_get           64u      Cumulative number of retrieval requests
cmd_set           64u      Cumulative number of storage requests
get_hits          64u      Number of keys that have been requested and 
                           found present
get_misses        64u      Number of items that have been requested 
                           and not found
evictions         64u      Number of valid items removed from cache                                                                           
                           to free memory for new items                                                                                       
bytes_read        64u      Total number of bytes read by this server 
                           from network
bytes_written     64u      Total number of bytes sent by this server to 
limit_maxbytes    32u      Number of bytes this server is allowed to
                           use for storage. 
threads           32u      Number of worker threads requested.
                           (see doc/threads.txt)

Memcached and Java

distributed memcached and connection pooling

Distributed caching is done by associating a given key with a server instance running memcached. That association must be consistent so that you only have to perform a lookup on one server to determine if data has been cached for that key. This is done with a consistent key hashing function and a continuum. You can imagine a continuum as being a circle with placeholders for your memcached servers spaced around the edge. Each server instance gets multiple placeholders around the circle (100 is a good number).

Few properties that you need to set to start with memcached is

A list of server

// Each host:port are separated by a blank space.

List<InetSocketAddress> serverList = AddrUtil.getAddresses(host:port host2:port2 host3:port3);

// The number of memcached client you would want to have, you would need only one if all you are going to do is async(non-blocking) //operation, if you would like to do some sync operation as well then may be you can create multiple instance of the memcached client.

Read here

int numOfMemcacheClient = x;

//The MemcachedClient is a single-threaded client to each of the Memcached server in the pool

MemcachedClient client = new MemcachedClient(new DefaultConnectionFactory() or new KetmaConnectionFactory(), serverList);

Memcached Stats
Two Java Memcached Client available :
2) spymemcached


Some good link on Memcached:
1) using memcached with java by Sacharya
2) A good pdf

Memory Analyzer

Memory Analyzer

Tools for analyzing the heap dump

1) Java jhat only for jdk 1.6 onwards

2) Eclipse Memory Analyzer

3) Visual VM

Interview Question – Part I

1) Given a Char[] of “This is my name”, come up with a Char[] of “name my is this”. The program should use as less memory as possible

Soln: First reverse the whole Char[] using Char temp, the new Char[] will be “eman ym si siht” and then reverse each word so the resultant Char[] will be “name my is this”

2) From the website read data and then post it to a URL, you don’t have any control over the data that you are reading from the website, means the data size can be anything and it can take min, hour to complete.

So write a program so that you timeout on a pre determined time while posting the data to the URL.

HttpURLConnection setConnectionTimeOut, setReadTimeout are good for what they have meant for, but what if the posting of data it self takes a lot of time and you want to set the time out on that particular operation.

Soln: Create a new Thread in your main thread, log the start time and then start a new task in the new Thread which reads the data posted on the website and then open a connection to the url and then post the data to that url.

Outside of the Thread that is in the main thread check the time see if the timeOut time is equal to CurrentTime – startTime if not then in a while loop Sleep for some constant interval wake up and see the currentTime – StartTime is equal to timeOut or if the thread is no longer alive.

If the  timeout time has been passed and thread is still alive then stop the thread, or if thread is completed before the timeout time has been passed, then exit gracefully.

3) Create a webpage which will pull all the files from a given directory in the filesystem.
Once user selects a file display the first 2 line and last 2 line of the file.


4) There are 5 millions records in a CSV file.

Sample record

1) userId1, movies, sports
2) userId2, news, movies

a) So basically each record has a userId and then set of tags associated with them.
Come up with number of user associated to each tag.


1) Start reading the file read something like 200 record give to ExecutorService as a task to parse them and then store the results in a hashmap (key – tag, value – counter)

2) Consolidate all the hashmap value into one.

Use something like synchronizers like CountDownLatch instead of wait and notify for figuring out when all the task has been complete and then consolidate.

I gave the answer that read one line at a time and send it to Executor service as a task and add the counter to the concurrent hash map, but here the problem is because we are using concurrentHashMap we will be blocked to increment the counter.

b) Now tag are associated with one or more tag like TV is associated with soap and sports and then sports is associated with cricket and tennis and so on.

So now find all the people associated with a tag and their associated tag, so basically find all the people associated with TV, soap, sports, cricket, tennis


Create a list of tag that is associated with a given tag

Start parsing the file and then userId in a list if any one of his tag is the tag list

5)  You have a list of number 1 to 9

1 2 3 4 5 6 7 8 9

Now all you can do is either you can combine the number like 12 or 23 or 34 or you can add a + symbol between 1 and 2, 3 and 4

So come up with the combination and + sign so that

1 2 3 4 5 6 7 8 9 = 99


1 + 2 + 3 + 4 + 5 + 67 + 8 + 9 = 99

6) You have a stack of number, at any given point of time tell what is the minimum number available in the stack

So for Example the stack is like this





So in this case the minimum number is 4, once you pop out 5 the minimum is still 4 and then when you pop out 4 the minimum is 7


maintain two stack so this is how they will look like

Enter 7

7 7

Enter 9


7 7

Enter 4


9 4

7 7

Enter 5



9 4

7 7

Now pop out 5

Compare 5 with the minimum stack top element 5 is big so don’t remove 4 from the other stack

Now pop out 4

as 4 is available in the minimum stack remove 4 from both the stack and so on.

Environment Setup

Today we will discuss how do we setup our working environment.

After we complete this exercise we will have the following things.

Linux machine running with tomcat 6.0.14,  jdk, axis2 1.3


Go to and download the bin file for what ever version you need, but here I am going to download the

Copy the downloaded file to /usr/java folder

In my case it is jdk-1_5_0_14-linux-i586.bin

First make the file executable by running

chmod +x jdk-1_5_0_14-linux-i586.bin

And then run(execute) the file


A new folder with the name jdk1.5.0_14 will be created.

Set the JAVA_HOME and PATH

You can do this in two ways

1) edit .bash_profile file in your home direcory and append the lines, this will set it for your user

export JAVA_HOME=/usr/java/jdk1.5.0_14
export PATH=$JAVA_HOME/bin:$PATH

2) make a file in /etc/profile.d and write the same two line in this file
export JAVA_HOME=/usr/java/jdk1.5.0_14

export PATH=$JAVA_HOME/bin:$PATH
and once you added the above two lines in your file run
source /etc/profile.d/
and then check java version
java -version
You are all set.


Download the tomcat 6.0.14 version from this link to your system. You can download any other version that you need.

Copy the file to /usr/local/ and unzip the file by running the following command:

tar zvxf apache-tomcat-6.0.14.tar.gz

/usr/local is more like a standard then any thing else, you can install it any where you want.

After that you can delete the apache-tomcat-6.0.14.tar.gz file.


Download the axis 2 webapp and put in the tomcat webapp folder.

Start the tomcat server it will explode the war file.

Now you will get a WEB-INF/services folder in your exploded folder.

Copy your aar file restart the tomcat and you are good to go.

Memcached Ketama

A very nice explanation for Ketama can be found in the README file of one of the implementation of Ketama here in gituhub public repository or here.

Web Caching with Consistent Hashing

Consistent Hashing and Random Trees: Distributed Caching Protocols for Relieving Hot Spots on the World Wide Web


Today I am going to talk about our favorite java.lang.Math class.

We have know Math class for various reason, when we started learning about the Java final keyword, I am sure everybody must have got an example of Math class how it is a final class and no can override it. You cannot create an instance of this class because the constructor is a private method and it has all method as a static method.

Lately I have been struggling with a production problem, where once in a while my CPU usage goes double from the normal and then it says at that level till we restart the server.

I even noticed that even after taking out the production server from the load balancer which means no new request are coming the cpu doesn’t goes down.

Then we took some thread dump and this is what we found

*** "http-8080-11" daemon prio=1 tid=0x0873f498 nid=0x39b3 runnable [0x6c3fe000..0x6c3fefb0]
 at java.lang.StrictMath.floor(Native Method)
 at java.lang.Math.floor(
 at java.lang.Math.round(

We saw this couple of times in the past also but ignored it, but this time because we saw only this we started thinking what’s going on with Math.round method which we use a lot in our code.

And then what I dig into the Math source code and this is what I found.

Java uses native method for most of the Math utility.

Math.round does the following

public static long round(double a) {

return (long)floor(a + 0.5d);


public static double floor(double a) {

return StrictMath.floor(a); // default impl. delegates to StrictMath


public static native double floor(double a);

and this native method is killing it.

Then when I dig into the forums I found people are complaining about performance issue for most of the Math methods.

These are some example for writing your own Math class method:

public int round (double doubleValue){

 int roundedValue = 0;
 int truncValue = (int)doubleValue;
 if(doubleValue - truncValue > 0.5){
    roundedValue = truncValue + 1;
    roundedValue = truncValue;
 return roundedValue;

Thanks to this blog post contributor for throwing some light on the above issue.

Look at  this bug for StrictMath.floor(a);