I have been asked this question in an interview for a start up:
Design a counter for a website which tells how many visits happened to that website. A given website will have various webpages. How can we implement a counter for that.
I proposed using a counter variable which gets incremented every time there is a read request to that website. Then the interviewer gave me a signature of the following method and asked me to implement the following method which increments the count.
void incrementCount()
I suggested two approaches using:
Then interviewer asked me following questions:
How do you take care of locking contention between the two methods:
What happens when the machine on which the above routines are running is crashed, then the count will be lost.
For (1), I suggested using a read-write lock
For (2), I suggested updating the values in a db(or filesystem) occasionally
He asked what if there is a crash just before the machine is trying to update the db. In that case the count will not be exact. I mentioned that these counts are mostly used for analytics and I think it is okay if these are not accurate.