Search code examples
javamultithreadingatomicboolean

Is there a way to count accesing threads to a primitive variable?


I have a variable in my code, a simple primitive boolean x. Because of code complexity, I am not sure about the number of threads accessing it. Maybe it is never shared, or is used by only one thread, maybe not. If it is shared between threads, I need to use AtomicBoolean instead.

Is there a way to count threads accessing boolean x?

Until now I did a review of the code but it is very complex and not written by me.


Solution

  • If this is just for testing/debugging purpose, you could maybe do it this way:

    If not yet the case, expose the boolean via a getter and count the threads in the getter. Here is a simple example where I make a list of all the threads accessing the getter:

    class MyClass {
    
        private boolean myAttribute = false;
    
        private Set<String> threads = new HashSet<>();
        public Set<String> getThreadsSet() {
            return threads;
        }
    
        public boolean isMyAttribute() {
            synchronized (threads) {
                threads.add(Thread.currentThread().getName());
            }
            return myAttribute;
        }
    
    }
    

    Then you can test

    MyClass c = new MyClass();
    
    Runnable runnable = c::isMyAttribute;
    
    Thread thread1 = new Thread(runnable, "t1");
    Thread thread2 = new Thread(runnable, "t2");
    Thread thread3 = new Thread(runnable, "t3");
    
    thread1.start();
    thread2.start();
    thread3.start();
    
    thread1.join();
    thread2.join();
    thread3.join();
    
    System.out.println(c.getThreadsSet());
    

    This outputs:

    [t1, t2, t3]
    

    EDIT: Just saw that you added that the attribute is accessed via setter, you can adapt the solution and log Threads in the setter