Java :: Count the number of times a method is called
Contents
How to find how many times a method is used?
A general answer to this question would be something like this:
Static variable
|
|
Using static int
would seem a perfect solution. Static will share the instance variable count
among all instances of MyClass.
However, problem occurs in a multi threaded environment, as the count incrementation is not synchronised.
Multi-threaded
|
|
Now this works perfect in a multi-threaded environment.
Thread safe atomic class
Java provides a better option to use thread-safe increments through Atomic classes available in java.util.concurrent.atomic
packag.
|
|
Here is a good read about AtomicInteger vs static int
: Java - using AtomicInteger vs Static int
Author: Deepu Mohan Puthrote
Link: https://deepumohan.com/tech/java-count-number-of-times-method-is-invoked/
This work by Deepu Mohan Puthrote is licensed under a Creative Commons Attribution 4.0 International License