Skip to page content Skip to main navigation
English | Site Directory

e.g. "templates" or "datastore"

# The Java Servlet Environment

App Engine runs your Java web application using a Java 6 JVM in a safe "sandboxed" environment. App Engine invokes your app's servlet classes to handle requests and prepare responses in this environment.

- Selecting the Java API Version
- Requests and Servlets
- Responses
- The Request Timer
- The Sandbox
- The JRE White List
- Logging
- The Environment
- Quotas and Limits

## Selecting the Java API Version

App Engine knows to use the Java runtime environment for your application when you use the AppCfg tool from the Java SDK to upload the app.

As of this writing, there is only one version of the App Engine Java API. This API is represented by the `appengine-api-*.jar` included with the SDK (where `*` represents the version of the API and the SDK). You select the version of the API your application uses by including this JAR in the application's `WEB-INF/lib/` directory. If a new version of the Java runtime environment is released that introduces changes that are not compatible with existing apps, that environment will have a new version number. Your application will continue to use the previous version until you replace the JAR with the new version (from a newer SDK) and re-upload the app.

## Requests and Servlets

When App Engine receives a web request for your application, it invokes the servlet that corresponds to the URL, as described in the application's deployment descriptor (the `web.xml` file in the `WEB-INF/` directory). It uses the Java Servlet API to provide the request data to the servlet, and accept the response data.

App Engine uses multiple web servers to run your application, and automatically adjusts the number of servers it is using to handle requests reliably. A given request may be routed to any server, and it may not be the same server that handled a previous request from the same user.

The following example servlet class displays a simple message on the user's browser.

    import java.io.IOException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    public class MyServlet extends HttpServlet {
        public void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws IOException {
            resp.setContentType("text/plain");
            resp.getWriter().println("Hello, world");
        }
    }

## Responses

App Engine calls the servlet with a request object and a response object, then waits for the servlet to populate the response object and return. When the servlet returns, the data on the response object is sent to the user.

App Engine does not support sending data to the client, performing more calculations in the application, then sending more data. In other words, App Engine does not support "streaming" data in response to a single request.

If the client sends HTTP headers with the request indicating that the client can accept compressed (gzip'd) content, App Engine compresses the response data automatically and attaches the appropriate response headers. It uses both the `Accept-Encoding` and `User-Agent` request headers to determine if the client can reliably receive compressed responses. Custom clients can force content to be compressed by specifying both `Accept-Encoding` and `User-Agent` headers with a value of "gzip".

## The Request Timer

A request handler has a limited amount of time to generate and return a response to a request, typically around 30 seconds. Once the deadline has been reached, the request handler is interrupted.

The Java runtime environment interrupts the servlet by throwing a `com.google.apphosting.api.DeadlineExceededException`. If the request handler does not catch this exception, as with all uncaught exceptions, the runtime environment will return an HTTP 500 server error to the client.

The request handler can catch this error to customize the response. The runtime environment gives the request handler a little bit more time (less than a second) after raising the exception to prepare a custom response.

While a request can take as long as 30 seconds to respond, App Engine is optimized for applications with short-lived requests, typically those that take a few hundred milliseconds. An efficient app responds quickly for the majority of requests. An app that doesn't will not scale well with App Engine's infrastructure.

## The Sandbox

To allow App Engine to distribute requests for applications across multiple web servers, and to prevent one application from interfering with another, the application runs in a restricted "sandbox" environment. In this environment, the application can execute code, store and query data in the App Engine datastore, use the App Engine mail, URL fetch and users services, and examine the user's web request and prepare the response.

An App Engine application cannot:

- write to the filesystem. Applications must use the App Engine datastore for storing persistent data. Reading from the filesystem is allowed, and all application files uploaded with the application are available.
- open a socket or access another host directly. An application can use the App Engine URL fetch service to make HTTP and HTTPS requests to other hosts on ports 80 and 443, respectively.
- spawn a sub-process or thread. A web request to an application must be handled in a single process within a few seconds. Processes that take a very long time to respond are terminated to avoid overloading the web server.
- make other kinds of system calls.

### Threads

A Java application cannot create a new `java.lang.ThreadGroup` nor a new `java.lang.Thread`. These restrictions also apply to JRE classes that make use of threads. For example, an application cannot create a new `java.util.concurrent.ThreadPoolExecutor`, or a `java.util.Timer`. An application can perform operations against the current thread, such as `Thread.currentThread().dumpStack()`.

### The Filesystem

A Java application cannot use any classes used to write to the filesystem, such as `java.io.FileWriter`. An application can read its own files from the filesystem using classes such as `java.io.FileReader`. An application can also access its own files as "resources", such as with `Class.getResource()` or `ServletContext.getResource()`.

Only files that are considered "resource files" are accessible to the application via the filesystem. By default, all files in the WAR are "resource files." You can exclude files from this set using the appengine-web.xml file.

### java.lang.System

Features of the `java.lang.System` class that do not apply to App Engine are disabled.

The following `System` methods do nothing in App Engine: `exit()`, `gc()`, `runFinalization()`, `runFinalizersOnExit()`

The following `System` methods return `null`: `inheritedChannel()`, `console()`

An app cannot provide or directly invoke any native JNI code. The following `System` methods raise a `java.lang.SecurityException`: `load()`, `loadLibrary()`, `setSecurityManager()`

### Reflection

An application is allowed full, unrestricted, reflective access to its own classes. It may query any private members, use `java.lang.reflect.AccessibleObject.setAccessible()`, and read/set private members.

An application can also also reflect on JRE and API classes, such as `java.lang.String` and `javax.servlet.http.HttpServletRequest`. However, it can only access public members of these classes, not protected or private.

An application cannot reflect against any other classes not belonging to itself, and it can not use the `setAccessible()` method to circumvent these restrictions.

### Custom Class Loading

Custom class loading is fully supported under App Engine. Please be aware, though, that App Engine overrides all ClassLoaders to assign the same permissions to all classes loaded by your application. If you perform custom class loading, be cautious when loading untrusted third-party code.

## The JRE White List

Access to the classes in the Java standard library (the Java Runtime Environment, or JRE) is limited to the classes in the App Engine JRE White List.

## Logging

Your application can write information to the application logs using java.util.logging.Logger. Log data for your application can be viewed and analyzed using the Administration Console, or downloaded using appcfg.sh request_logs. The Admin Console can recognize the `Logger` class's log levels, and interactively display messages at different levels.

Everything the servlet writes to the standard output stream (`System.out`) and standard error stream (`System.err`) is captured by App Engine and recorded in the application logs. Lines written to the standard output stream are logged at the "INFO" level, and lines written to the standard error stream are logged at the "WARNING" level. Any logging framework (such as log4j) that logs to the output or error streams will work. However, for more fine-grained control of the Admin Console's log level display, the logging framework must use a `java.util.logging` adapter.

    import java.util.logging.Logger;
    // ...

    public class MyServlet extends HttpServlet {
        private static final Logger log = Logger.getLogger(MyServlet.class.getName());

        public void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws IOException {

            log.info("An informational message.");

            log.warning("A warning message.");

            log.severe("An error message.");
        }
    }

The App Engine Java SDK includes a template `logging.properties` file, in the `appengine-java-sdk/config/user/` directory. To use it, copy the file to your `WEB-INF/classes` directory (or elsewhere in the WAR), then the system property `java.util.logging.config.file` to `"WEB-INF/classes/logging.properties"` (or whichever path you choose, relative to the application root). You can set system properties in the `appengine-web.xml` file, as follows:

    <appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
        ...

        <system-properties>
            <property name="java.util.logging.config.file" value="WEB-INF/classes/logging.properties" />
        </system-properties>

    </appengine-web-app>

The Google Plugin for Eclipse new project wizard creates these logging configuration files for you, and copies them to `WEB-INF/classes/` automatically. For `java.util.logging`, you must set the system property to use this file.

## The Environment

All system properties and environment variables are private to your application. Setting a system property only affects your application's view of that property, and not the JVM's view.

You can set system properties and environment variables for your app in the deployment descriptor.

App Engine sets the following system properties when it initializes the JVM on an app server:

- `file.separator`
- `path.separator`
- `line.separator`
- `java.version`
- `java.vendor`
- `java.vendor.url`
- `java.class.version`
- `java.specification.version`
- `java.specification.vendor`
- `java.specification.name`
- `java.vm.vendor`
- `java.vm.name`
- `java.vm.specification.version`
- `java.vm.specification.vendor`
- `java.vm.specification.name`
- `user.dir`

## Quotas and Limits

Each incoming request to the application counts toward the Requests quota.

Data received as part of a request counts toward the Incoming Bandwidth (billable) quota. Data sent in response to a request counts toward the Outgoing Bandwidth (billable) quota.

Both HTTP and HTTPS (secure) requests count toward the Requests, Incoming Bandwidth (billable) and Outgoing Bandwidth (billable) quotas. The Quota Details page of the Admin Console also reports Secure Requests, Secure Incoming Bandwidth and Secure Outgoing Bandwidth as separate values for informational purposes. Only HTTPS requests count toward these values.

CPU processing time spent executing a request handler counts toward the CPU Time (billable) quota.

For more information on quotas, see Quotas, and the "Quota Details" section of the Admin Console.

In addition to quotas, the following limits apply to request handlers:

Limit | Amount
--- | ---
request size | 10 megabytes
response size | 10 megabytes
request duration | 30 seconds
simultaneous dynamic requests | 30 *
maximum number of application files | 1,000
maximum number of static files | 1,000
maximum size of an application file | 10 megabytes
maximum size of a static file | 10 megabytes
maximum total size of all application and static files | 150 megabytes

* An application can process around 30 active dynamic requests simultaneously. This means that an application whose average server-side request processing time is 75 milliseconds can serve up to (1000 ms/second / 75 ms/request) * 30 = 400 requests/second without incurring any additional latency. Applications that are heavily CPU-bound may incur some additional latency in long-running requests in order to make room for other apps sharing the same servers. Requests for static files are not affected by this limit.