Search code examples
javadebuggingconcurrentmodification

Getting stack traces for all threads of a concurrent access:


We seem to have a concurrent access to a method in our code. A workaround would be to synchronize that method. But that would not fix the root cause: there should be no such concurrent access in the first place.

How to get the stack traces of all threads that access this method, but only in the case there is a concurrent access?

Another option would be detecting that the synchronization would block - before it actually blocks.


Solution

  • Try using Reentrant lock to suit the purpose. Here is the sample code:

    private final ReentrantLock lock = new ReentrantLock();
    
          public void sampleLock() {
            lock.lock();
            try {
              Thread.sleep(5000);
            } catch (InterruptedException e) {
              System.out.println(Thread.currentThread().getName() + "interrupted");
            }
            lock.unlock();
          }
    

    If any other method wants to access sampleLock() method then lock.isLocked() will tell if it is used by any other thread. Please go through the Oracle documentation for the same. https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReentrantLock.html