We have few classes which extends a base class. We noticed that we use quit a few sleeps method and we wanted to log when a sleep occurs. Is there a way to override the Thread.sleep method in which I can add some custom logic ( ie logging) and then just call the actual Thread.sleep()? This way I wouldn't have to change all the places where Thread.sleep is being used in my bases classes. I'm open to other options as well.
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
You cannot override
Thread.sleep
method, you cannot instrument or transform it either as it's a native method. One way is to automatically add logging to all places which call Thread.sleep using a Java Agent.While the following approach works and is quite fun, in your case it's probably much better to refactor all calls to the
Thread.sleep
into a separate method and add the logging there.You can find an introduction to Java Agents here. In a nutshell it's a special mechanism which allows (among other) transformation of loaded Java byte code. The following example of an Java Agent class automatically enhances all calls to the Thread.sleep with System.out logging and measure time spent in the method:
You will need to compile it into a loggerAgent.jar file and include the following META-INF/MANIFEST.MF in it:
Download JavaAssist and put it into same folder as your jar with compiled Agent. Run your application with parameter
-javaagent:loggerAgent.jar
.You can download a full example. Just extract it, open folder release and run the application with
java -cp loggerAgent.jar -javaagent:loggerAgent.jar Test
More information and more examples can be found in this excellent article.