English ▼
Skip to page content Skip to main navigation
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 Domains
- Requests and Servlets
- Request Headers
- Responses
- The Request Timer
- The Sandbox
- The JRE White List
- Logging
- The Environment
- 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.

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 Domains

App Engine determines that an incoming request is intended for your application using the domain name of the request. A request whose domain name is `http://your_app_id.appspot.com` is routed to the application whose ID is `your_app_id`. Every application gets an `appspot.com` domain name for free.

`appspot.com` domains also support subdomains of the form `subdomain.your_app_id.appspot.com`, where `subdomain` can be any string allowed in one part of a domain name (not `.`). Requests sent to any subdomain in this way are routed to your application.

You can set up a custom top-level domain using Google Apps. With Google Apps, you assign subdomains of your business's domain to various applications, such as Google Mail or Sites. You can also associate an App Engine application with a subdomain. For convenience, you can set up a Google Apps domain when you register your application ID, or later from the Administrator Console. See Deploying your Application on your Google Apps URL for more information.

Requests for these URLs all go to the version of your application that you have selected as the default version in the Administration Console. Each version of your application also has its own URL, so you can deploy and test a new version before making it the default version. The version-specific URL uses the version identifier from your app's configuration file in addition to the `appspot.com` domain name, in this pattern: `http://version_id.latest.your_app_id.appspot.com` You can also use subdomains with the version-specific URL: `http://subdomain.version_id.latest.your_app_id.appspot.com`

The domain name used for the request is included in the request data passed to the application. If you want your app to respond differently depending on the domain name used to access it (such as to restrict access to certain domains, or redirect to an official domain), you can check the request data (such as the `Host` request header) for the domain from within the application code and respond accordingly.

If your app uses backends, you can address requests to a specific backend and a specific instance with that backend. For more information about backend addressability, please see Properties of Backends.

## 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. If your application uses backends, it invokes the servlet defined in `backends.xml` or `backends.yaml`, depending on which configuration file your application uses. See Backend Configuration for more information.

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.

By default, each web server processes only one request at a time. If you mark your application as thread-safe, App Engine may dispatch multiple requests to each web server in parallel. To do so, simply add a `<threadsafe>true</threadsafe>` element to `appengine-web.xml` as described in Using Concurrent Requests.

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");
        }
    }

## Request Headers

An incoming HTTP request includes the HTTP headers sent by the client. For security purposes, some headers are sanitized or amended by intermediate proxies before they reach the application.

As a service to the app, App Engine adds an additional header: `X-AppEngine-Country` This header's value represents the country from which the request originated, as an ISO 3166-1 alpha-2 country code. App Engine determines this code from the client's IP address.

## 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 (gzipped) 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".

If you access your site while signed in using an administrator account, App Engine includes per-request statistics in the response headers. The header `X-AppEngine-Estimated-CPM-US-Dollars` represents an estimate of what 1,000 requests similar to this request would cost in US dollars. The header `X-AppEngine-Resource-Usage` represents the resources used by the request, including server-side time as a number of milliseconds.

## The Request Timer

A request handler has a limited amount of time to generate and return a response to a request, typically around 60 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 60 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.

Backends allow you to avoid this request timer; with backends, there is no time limit for generating and returning a request.

## 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/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/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 several system properties that identify the runtime environment:

1. `com.google.appengine.runtime.environment` is `"Production"` when running on App Engine, and `"Development"` when running in the development server.

   In addition to using `System.getProperty()`, you can access system properties using our type-safe API. For example:

       if (SystemProperty.environment.value() ==
           SystemProperty.Environment.Value.Production) {
           // The app is running on App Engine...
       }

2. `com.google.appengine.runtime.version` is the version ID of the runtime environment, such as `"1.3.0"`. You can get the version by invoking the following: `String version = SystemProperty.version.get();`
3. `com.google.appengine.application.id` is the application's ID. You can get the ID by invoking the following: `String ID = SystemProperty.applicationId.get();`

App Engine also 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

Google App Engine allocates resources to your application automatically as traffic increases to support many simultaneous requests. However, App Engine reserves automatic scaling capacity for applications with low latency, where the application responds to requests in less than one second. Applications with very high latency (over one second per request for many requests) are limited by the system, and require a special exemption in order to have a large number of simultaneous dynamic requests. If your application has a strong need for a high throughput of long-running requests, you can request an exemption from the simultaneous dynamic request limit. The vast majority of applications do not require any exemption.

Applications that are heavily CPU-bound may also incur some additional latency in order to efficiently share resources with other applications on the same servers. Requests for static files are exempt from these latency limits.

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

Data sent in response to a request counts toward the Outgoing Bandwidth (billable) limit.

Both HTTP and HTTPS (secure) requests count toward the Requests, Incoming Bandwidth (billable), and Outgoing Bandwidth (billable) limits. 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.

For more information on system-wide safety limits, see Limits, and the "Quota Details" section of the Admin Console.

In addition to system-wide safety limits, the following limits apply specifically to the use of request handlers:

Limit | Amount
--- | ---
request size | 32 megabytes
response size | 32 megabytes
request duration | 60 seconds
maximum total number of files (app files and static files) | 10,000 total 1,000 per directory
maximum size of an application file | 32 megabytes
maximum size of a static file | 32 megabytes
maximum total size of all application and static files | 150 megabytes