Home > Enterprise >  Find out all java code places where a blocking operation happens
Find out all java code places where a blocking operation happens

Time:08-26

In our Netty application. We are moving all blocking calls in our code to run in a special backgroundThreadGroup.

I'd like to be able to log in production the threadName and the lineNumber of the java code that is about to execute a blocking operation. (i.e. sync File and Network IO)

That way I can grep for the logs looking at places were we might have missed to move our blocking code to the backgroundThreadGroup.

Is there a way to instrument the JVM so that it can tell me that?

CodePudding user response:

Depends on what you mean by a "blocking operation".

In a broad sense, any operation that causes a voluntary context switch is blocking. Trying to do something special about them is absolutely impractical.

For example, in Java, any method containing synchronized is potentially blocking. This includes

  • ConcurrentHashMap.put
  • SecureRandom.nextInt
  • System.getProperty

and many more. I don't think you really want to avoid calling all these methods that look normal at a first glance.

Even simple methods without any synchronization primitives can be blocking. E.g., ByteBuffer.get may result in a page fault and a blocking read on the OS level. Furthermore, as mentioned in comments, there are JVM level blocking operations that are not under your control.

In short, it's impractical if not impossible to find all places in the code where a blocking operation happens.

If, however, you are interested in finding particular method calls that you believe are bad (like Thread.sleep and Socket.read), you can definitely do so. There is a BlockHound project specifically for this purpose. It already has a predefined list of "bad" methods, but can be customized with your own list.

  • Related