Skip to main content

Avoid instantiating a class for each message

Sometimes you will need to do some work on a message which cannot be done by generic components or by using a Talend DI Job. To do this you might choose Java and might want to encapsulate the code in a class or a bean. This is a very powerful mechanism and can be very useful, but can also cause performance issues if it is not implemented in an efficient manner.

If you have a Route that might process thousands of messages an hour, having a new class instantiated for every message is not very efficient in terms of memory usage. Doing this inefficiently can increase the likelihood of facing the “Exception in thread "main" java.lang.OutOfMemoryError: Java heap space” exception. In order to avoid this it is a good idea to build your classes so that they do not need to be instantiated for every message. If possible instantiate them at the beginning of the Route and store them in a registry.

Talend provide a component for doing this called the cBeanRegister component. This component will register the created object and make it available at any point in the Route. If it is a simple bean you can reference it in the many ways described in the documentation using the inbuilt functionality. If you need to use it in a cProcessor component, you can retrieve it using a variation on following code:

//Get Camel Context
Map<String, CamelContext> contextMap = getCamelContextMap();
DefaultCamelContext dcc = (DefaultCamelContext)contextMap.get(jobName+"-ctx");   

//Get the object stored in the registry 
MyObject myObject = (MyObject)dcc.getRegistry().lookup("myObjectReference");

Doing this can dramatically improve the memory usage and performance of your Routes.

Did this page help you?

If you find any issues with this page or its content – a typo, a missing step, or a technical error – let us know how we can improve!