Press "Enter" to skip to content

Solving the Jetty file locking problem when starting it programmatically

In the past few weeks I was required to create a prototype for the frontend of a project and because the focus is only on the frontend, I’ve chosen Jetty to create a simple mock server that would respond with simple JSON messages or stream some image files. I also use Jetty to serve the static files, like static images, CSS, JS that I am continuously modifying while developing the new frontend. Because I am developing on Windows, I have run quite soon into the file locking problem.

The solution is to simply set the useFileMappedBuffer parameter false. While this is easy if you use Maven to start Jetty or you use an XML file to configure it, I prefer to start it programmatically from Java. To solve this programmatically you need to simply add this initial parameter to your WebAppContext:

webAppContext.getInitParams().put("org.eclipse.jetty.servlet.Default.useFileMappedBuffer", "false");  

For an example of how I start my Jetty server programmatically, here’s my source code:

package core;

import org.eclipse.jetty.server.Server;  
import org.eclipse.jetty.server.handler.HandlerCollection;  
import org.eclipse.jetty.webapp.WebAppContext;

 * Created by Laszlo Gazsi on 4/19/2016.
public class Jetty {

    public static void main(String[] args) throws Exception {

        Server server = new Server(88);

        WebAppContext webAppContext = new WebAppContext();

        webAppContext.getInitParams().put("org.eclipse.jetty.servlet.Default.useFileMappedBuffer", "false");

        webAppContext.addServlet(ResourceServlet.class, "/json");
        webAppContext.addServlet(StreamServlet.class, "/stream");

        HandlerCollection handlers = new HandlerCollection();