Skip to content

Category: Java

Advanced instrumentation with ByteBuddy Agent

Reading Time: 7 minutes

The Aspect-Oriented Programming paradigm allows to achieve a great level of Separation of Concerns (SoC) in the application’s codebase. All the necessary components that do not relate to the business logic directly, like security, metrics, logging, etc., can be nicely isolated into auxiliary modules that will be wired up with the business logic indirectly, usually during the compilation or in runtime.

In the Java world, there are not so many frameworks for AOP. The notable ones are AspectJ and Spring AOP. Both balance the complexity and functionality. The process of attaching the extra modules to the business logic is called weaving. In short, AspectJ supports compile-time weaving that modifies output class files (variation – post-compile weaving is used for 3rd party classes), and load-time weaving that intercepts the classloader and modifies the classes in the process of defining them to the JVM. Alternatively, Spring AOP has a much more simple model, it allows for runtime weaving only that works just for Spring Beans defined in the Application Context. The weaving is done via proxies generated by Spring.

In addition to these two frameworks, there is one more great library that exists for pretty similar objectives, it is called Byte Buddy, developed by Rafael Winterhalter. This library is pretty well known for its highly simplified and convenient facilities that allow runtime code generation and modification. Byte Buddy makes it easy to create a new type that can redefine existing types, intercept methods, and much more to that. But in addition, it can also change the behavior of existing classes. This is done via Byte Buddy Agent that can operate with Java Instrumentation API to do necessary changes to type definitions. This may sound similar to AspectJ load-time weaving, which in fact is, but practically there is a big difference between the two. The main benefit of using Byte Buddy is simplicity. The API is very intuitive, the extra tooling is not required, and overall integration of it does not force any changes in the build process, run configuration or so.

Now it is time to stop the theory and apply the Byte Buddy in practice. A simple, yet important example could be the detection of certain methods invocations. In fact, this idea has been inspired by the BlockHound project (detector of blocking calls from non-blocking reactive threads), developed by Sergei Egorov.

Leave a Comment

Short Tip on Java: throw multiple Exceptions at once

Reading Time: 5 minutes

Exceptions in Java are intended to interrupt the execution flow in unexpected situations. But there might be a need to continue the execution without interruption, still being able to collect all the errors that occurred before.

An abstract example of such a flow can be a Backup Manager. To increase reliability, it might need to save backups to multiple targets. Those can be a local file system, an external file system, and some cloud provider.

The whole flow will consist of three steps, one for each type of backup target. But the execution of these steps is unpredictable. Exceptions may happen at any moment, and the rest of the flow will be interrupted, which is bad, as one broken target may destroy the whole reliability concept.

Of course, Java has mechanisms to prevent interruption. Using try-catch block for each of the steps will guarantee that all the steps will be executed. The only problem here is that at the end of the execution there will be too little information about what went wrong.

Exceptions may be collected to some list and processed afterward. But in some cases, there is no need for such sophisticated solutions. The only needed outcome may be a single exception that will just explain the whole execution and what was wrong during it.

Leave a Comment

How to understand Class.isAssignableFrom() in Java

Reading Time: 4 minutes

Java has quite a few ways to compare types of objects. Most well know are:

  • operator instanceof;
  • method Class.isInstance(Object obj);
  • method Class.isAssignableFrom(Class<?> cls).

The logic of the first two can be quite easily inferred based on the names. But the last one needs a bit of thinking to completely interpret it. So how to understand it once and forever?

Leave a Comment

Java, let me follow code style

Reading Time: 5 minutes

Developers spend much more time reading the code rather than writing. For that reason readability and “clean code” practices are in general is very important. There is a lot of different rules exists to help developers structure their code in a way so it needs less effort for understanding and in maintenance. On top, there are also tools created to enforce those rules.

Now to the code. Looking at it from the high-level perspective it is easy to distinguish bigger blocks, like classes (not necessarily to follow the OOP paradigm, by “class” any top-level grouping can be mentioned) and their members. And the order of these members in class is very important.

There is a couple of most popular recommendations to that.

First one, it comes from the code style guidelines published by big tech players like Google or Oracle says that it is important to order class members by the level of exposure. This order fits good the code written in the form of a library:

  • public members – class API, is the most important part, must fall into consumer’s eye as soon as possible so it stands at the first position;
  • protected members – internal API, still important as it can be overridden thus needs to be at the second position;
  • private members – pure internals, can be placed at the very last position.

An alternative recommendation suggested by Robert C. Martin can be formulated much more easily: order of the members must be defined like chapters in the fiction book, they must follow the execution flow “story” and explain the code without a need to jump around the text up and down. This style fits good typical services that define pure business logic, set of operations required to execute some user scenario.

So for the second approach there is not much what can be automatically enforced, whereas for the first one it is an opposite situation. But even if the idea is simple, sometimes it is just impossible to overcome language limitations and entirely follow the code style “public” -> “protected” -> “private”.

Leave a Comment
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept