Java :: Count the number of times a method is called
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]
1