0

How can I calculate how many times function has been called for each thread?

So suppose that there are many flows, which are calling the same function. I have to change them all in order to pass some parameter, which will keep the the number of calls. But I am looking for the ways to not modify the functions signature, but instead keeping thread local variables and printing its value from some time.

Vardan Hovhannisyan
  • 1,101
  • 3
  • 17
  • 40

3 Answers3

1

I guess you can do it using simple synchronized block

//a counter declared in your class
private static int counter;

...
...

public void someMethod foo() {  
        synchronized(counter){  
            counter++;  
        }  


        //rest of your logic
        ...
    }  
}
Raman Sahasi
  • 30,180
  • 9
  • 58
  • 71
0

If you want count the total number of times a method was called, you can use a static AtomicInteger or AtomicLong.

class C {
    private static final AtomicInteger count = new AtomicInteger();
    public void m() {
        count.getAndIncrement();
        //... the rest of the method
    }
    public static void getCount() {
        return count.get();
    }
}

If you want to keep a separate count for each thread, you need a map of counters

class C {
    private static final ConcurrentHashMap<Long, AtomicInteger> counts = new ConcurrentHashMap<>();
    void m() {
        counts.putIfAbsent(Thread.currentThread().getId(), new AtomicInteger(0));
        counts.get(Thread.currentThread().getId()).getAndIncrement();
        //... the rest of the method
    }

    public static Map<Long, AtomicInteger> getCount() {
        return counts;
    }
}
noscreenname
  • 3,314
  • 22
  • 30
-1

Vardan Hovhannisyan

You must use synchronized variable inside the function or method, sycrhonize is necessarie to don't crahs between threads during executing and counting, for mantein de correct value.

public class exemplesyn {
      //Count variable
      private Integer countsychronized =0;

      //Methode to count execution
      public void executedmethodeToCount(){
           this.countSychronized();
           //Code to execute
      }

      //Synchroniced methode to count
      public synchronized void countSychronized (){
         this.countsychronized++;
      }
}
hugffgm
  • 1
  • 1