It is required to count the number of calls ( set and get ) to the private static field of the class MyClass .

Is the correct approach to addressing this issue applied below?

 class MyClass { private static String str = "example string"; private static Integer countGetSet = 0; public static String getString() { countGetSet++; return str; } public static void setString(String inStr) { str = inStr; countGetSet++; } public static Integer getСountGetSet() { return countGetSet; } } 

    1 answer 1

    It all depends on the situation.

    If you have one object of this class, then you can wrap it in a proxy and increment the counter with each method call. Thereby you keep the measured class intact. This can be done either through a стандартный прокси , or through AspectJ , or through a mockito .

    You can also use design patterns and create a декоратор for this class. When you call a method, you increment the counter and then delegate the execution to the method of the class being measured.

    Your version is the simplest, but there are problems with multithreading. This code is not thread-safe . Instead of an Integer use AtomicInteger to make it so.

    • if to use AtomicInteger will be thread-safe? - AdamSkywalker
    • @AdamSkywalker will be - Bohdan Korinnyi
    • @BogdanK did not guess - AdamSkywalker
    • @AdamSkywalker This code is not thread-safe. Instead of an Integer, use AtomicInteger to make it so. - Bohdan Korinnyi
    • @BogdanK hints to synchronize access to a variable did not come - AdamSkywalker