How to find how many times a method is used?
A general answer to this question would be something like this:
1 2 3 4 5 6 7 8 9 |
|
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
Now this works perfect in a multi-threaded environment.
Java provides a better option to use thread-safe increments through Atomic classes available in java.util.concurrent.atomic
packag.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
Here is a good read about AtomicInteger vs static int
: Java – using AtomicInteger vs Static int