Fork this page on GitHub

Dynamically reload code

Reload Java or Scala code without restarting your web app

If you are building a web application you want to be able to create and edit Java and Scala code on the fly without having to stop and restart your web container for each code change.

JRebel to the rescue!

JRebel allows you to hot reload bytecode on the fly in your application without having to restart your web container.

Here's how you can use it in a web application with Scalate.

Now if your code is compiled by your IDE or a build process, the classes are automatically reloaded on the fly. Neat eh!

For example if you run the following in another shell

mvn scala:cc

Then as you edit your scala code it will be recompiled using Scala's incremental compiler, then JRebel will auto-reload any recompiled classes.

Using the Scalate JRebel plugin

If you have templates which depend on Scala code thats reloaded by JRebel, it might be that the templates by default are not auto-reloaded by JRebel. This is because by default JRebel is not aware of the source & classes directories used by Scalate to generate Scala code for each template and compile it.

The easiest thing to do is to just depend on the scalate-jrebel plugin in your web application. This is a JRebel plugin which listens to classes being reloaded in JRebel and it flushes all the Scalate template classes to ensure that your template is recompiled against the latest code.

So for example if you are using maven then add this profile to your web application pom.xml

<profiles>
  <profile>
    <id>jrebel</id>
    <dependencies>
      <dependency>
        <groupId>org.fusesource.scalate</groupId>
        <artifactId>scalate-jrebel_2.10</artifactId>
        <version>${scalate-version}</version>
      </dependency>
    </dependencies>
  </profile>
</profiles>

If you then run your web application as follows (assuming you've defined MAVEN_OPTS) as specified above)

mvn jetty:run -Pjrebel

Things to watch

We've found that if you use _scalate directory in the WEB-INF directory when running your web app using jetty:run JRebel really slows down the Scalate recompile step hugely; so its better to let Scalate use a work directory outside of the web application.

This should happen by default now; if not specify the scalate.workdir system property to be the work directory you want scalate to use. For example

mvn -Dscalate.workdir=/tmp/_scalate jetty:run