0

I want to count the number of times my servlet program ran in the application.

I have used count variable in doPost method of the servlet. Every time I run the application the count will increase. But if close the editor (eclipse/netbeans) or if I close the project then my count will be reset to zero.because my servlet container will also stop running.

One way is to save my count value in data base. Is there any other way apart from database where I can store my count value even after closing the editor or project. Can I store my count value in file?

HaveNoDisplayName
  • 8,291
  • 106
  • 37
  • 47
praveen sangalad
  • 338
  • 2
  • 14
  • 2
    technically saving/writing the count value in a file can be done the same way you save it in db. have you tried it? – Baby Sep 28 '15 at 05:41
  • Yes, you can store it in a file. You store in: File, Database, Registry, Cloud, or anywhere else you want. – Andreas Sep 28 '15 at 05:50

1 Answers1

2

In general you can store the count value whenever you want, file, database of any kind and so on.

However I would like to mention that servlets in general are designed to run in environments where many users can access the servlet simultaneously, so you always have to think about the synchronization. Multiple instances of the serlvet class can exist (it's up to you web container when to create them).

In general what you need to do is:

  • Get the current value
  • Increase the value by 1
  • Store the value

Now this thing has to be carefully implemented. Depending on the underlying layer you might want to consider using Transactions:For example for postgesql

Another example is using a NoSQL store like Redis: Read Pattern counter section

The best way to implement a distributed counter really depends on the underlying storage so its hard to advice on anything more specific, the choice is yours.

Another aspect I would like to mention is a distributed nature of web application.

If its a real world application, eventually you might want to run it on multiple service and 'scale it out' (at least its a trend in a modern server side software in my opinion).

From this perspective, the application can't really use local file and, say, windows registry because the file system is not a distributes thing (unless you use a distributed file system).

Hope, this helps

Community
  • 1
  • 1
Mark Bramnik
  • 39,963
  • 4
  • 57
  • 97
  • 1
    I agree in general, except for "Multiple instances of the serlvet class can exist (it's up to you web container when to create them)". The servlet specification explicitely says: "the servlet container must use only one instance per servlet declaration.". – JB Nizet Sep 28 '15 at 06:29