Groovy – making existing objects refreshable
In the last post I described the basic principles I found behind the scenes of GroovyScript refresh. Now imagine that you want to create your own long living Groovy instances with auto-refresh behaviour when source code changes. You can use out-of-the-box Spring support – but there are some limitations I stated in the previous article.
In this post I am going to present an alternative solution that addresses some of the painful issues I noticed. As I stated before, key is to wrap the reference to Groovy instance into an another object managed by the Java class loader and that is exactly the main point of the solution presented.
My inspiration was based on the Spring’s approach to the issue. It wraps each and every groovy instance into the JDK proxy, that is safe to handle out and store anywhere developer wants (even in the long living scopes). Implementation of this proxy delegates method call to inner Groovy instance, but is also able to check whether the underlying code haven’t changed. If it has, it drops current Groovy instance and creates new one, that immediately initializes by configured dependency injection rules.
To overcome the main issues connected with Spring’s solution, I decided to:
- base my solution on CgLib proxy instead of JDK Proxy – this way we could also use methods of the Java classes our Groovy class extends from and not only methods declared on interfaces
- use GroovyScripting engine instead of simple GroovyClassloader to reflect changes not only in the instantiated class itself, but also in classes it uses
- add easy method for unwrapping inner Groovy instance – so we could easily use methods declared on the Groovy class (for example in templating engines) without need of having Java interface that contains them (though programming for interfaces is a good approach, I don’t see and advantage of having interface ever having only single implementation)
- provide callback for custom initialization logic after instance recreation (refresh)
Note: please, be warned, this post contains a lot of code that might not be as readable as I have wished it to be. If you feel that you don’t get the point, download the sources with JUnit tests and feel free to fiddle with it a little bit. I am sure the topic is not so hard to undestand as it looks for the first sight.
Enough talking – let’s look at the code. I use unified my own interface ScriptingFactory for creating new scripting instances (I try to abstract from the underlying Groovy scripting support at the base interfaces):
For this interface there are two Groovy implementations – ProductionGroovyFactory and DevelopmentGroovyFactory.
ProductionGroovyFactory creates instances of Groovy classes that never refresh. Returned instances are pure instances of specified Groovy classes. References passed around will potentialy prevent Groovy class and classloader being garbage collected, but that wouldn’t be likely necessary in production (no refreshes occur there). On the other hand this implementation represents easiest and most performant way to providing Groovy instances. This implementantion is not interesting for the sake of this article, so I skip it.
DevelopmentGroovyFactory creates instances of Groovy classes wrapped in proxies. This will allow us to safely hand around references to those instances without worrying about refresh behaviour when underlying source code changes. Proxies will maintain refreshing logic, checking source code change in specified intervals and eventually freeing old instances and creating new fresh one based on new classes corresponding to latest source code state.
Moreover the system is setup the way that programmer doesn’t need to take care of proper reference handling to avoid PermGenSpace memory leaks. Returned references doesn’t have anything common with Groovy class – they are derived from first Java ancestor class in an ancestor hierarchy and implement all interfaces loaded by pure Java classloader. All Groovy related things are located in the proxy, so the swapping can be handled safely.
DevelopmentGroovyFactory wraps Groovy instances into the AOP dynamic proxy. This proxy always implements this interface:
As you can see proxy uses so called ProxyInstanceFactory for creating new inner instances of the Groovy classes when corresponding source code changes. This interface could be optionaly used not only for instantiation itself, but also for initial setup of the instance, such as dependency injection and so on.
Last piece of the puzzle is GroovyProxyMixin, that implements ScriptingProxy interface and REALLY does the magic around monitoring source code changes and reinstantiation of the inner Groovy instance. Let’s examine the code:
Example of the API usage
Thought horrible it might look like – the important side of the matter is how it’ll be used by the client code that will use this API. And there, I think, we are at the much more solid ground:
This doesn’t look difficult, does it?
References that you receive from the DevelopmentScriptingFactory could be passed around without fear of PermGenSpace leaks and yet the behaviour would dynamically adapt source code changes. In Java code we could safely cast to any of Java interfaces or Java classes our Groovy class extends from. When we need to use created Groovy instance in templating engine (such as Freemarker or Velocity) we could unwrap original Groovy instance from the returned ScriptingProxy, so the engine could call any method declared on the Groovy class by the reflection. Unwrapping inner instance is somewhat dangerous, but for the purpose of the templating activities we could afford this. Template engines usually create a context used for single request processing only, so the unwrapped instance references stored in such context will soon fade off as the request gets processed and context itself dies. Similarly we could safely store unwrapped Groovy instances into the request attributes or other short lived objects, making profit of the direct access to the Groovy class instance.
Source code with tests download
Here you can download source code with IntelliJ Idea project files to examine. I recommend to play with it a little bit in a debug mode, as well as creating some more tests on your own. After all, I could be terribly wrong, thought the tests confirm my theories.
What comes next …
There is yet another part of this serie, where I will present an integration of current solutions into the Spring via implementing BeanFactory and simple solution for refreshing Spring context trees when Spring configuration or any of the monitored bean changes. Will I make it till Christmas? I don’t know as there isn’t a comma of it written. Be patient, please …
Související články:
- The secret of Groovy script refresh
- Spring CgLib Dynamic AOP Proxies – proper Pointcut equals method is simply essential
- Testing Aspect Pointcuts – is there an easy way?
- Running AJAX with jQuery in Stripes Framework





Pokud by měl někdo zájem o reálné použití, napište mi na email – knihovnu jsme ještě drobet vyladili, našlo se pár nedokonalostí v integraci s Groovy. Máme i upgradovanou verzi pro Groovy 1.7, ve kterém jsme reportovali dokonce několik chyb s GroovyScriptEnginem a Springem souvisejících. Nyní ji pomaličku začínáme nasazovat produkčně na menších instalacích.
Aktualizoval jsem zdrojové kódy na naši poslední odladěnou verzi. Můžete stahovat tímto linkem:
http://files.novoj.net/GroovyIntegration/groovy-integration.zip