Building Lambda functions with Java - AWS Lambda

Building Lambda functions with Java

You can run Java code in AWS Lambda. Lambda provides runtimes for Java that run your code to process events. Your code runs in an Amazon Linux environment that includes AWS credentials from an AWS Identity and Access Management (IAM) role that you manage.

Lambda supports the following Java runtimes.

Java
Name Identifier Operating system Deprecation date Block function create Block function update

Java 21

java21

Amazon Linux 2023

Java 17

java17

Amazon Linux 2

Java 11

java11

Amazon Linux 2

Java 8

java8.al2

Amazon Linux 2

Lambda provides the following libraries for Java functions:

Important

Don't use private components of the JDK API, such as private fields, methods, or classes. Non-public API components can change or be removed in any update, causing your application to break.

To create a Java function
  1. Open the Lambda console.

  2. Choose Create function.

  3. Configure the following settings:

    • Function name: Enter a name for the function.

    • Runtime: Choose Java 17.

  4. Choose Create function.

  5. To configure a test event, choose Test.

  6. For Event name, enter test.

  7. Choose Save changes.

  8. To invoke the function, choose Test.

The console creates a Lambda function with a handler class named Hello. Since Java is a compiled language, you can't view or edit the source code in the Lambda console, but you can modify its configuration, invoke it, and configure triggers.

Note

To get started with application development in your local environment, deploy one of the sample applications available in this guide's GitHub repository.

The Hello class has a function named handleRequest that takes an event object and a context object. This is the handler function that Lambda calls when the function is invoked. The Java function runtime gets invocation events from Lambda and passes them to the handler. In the function configuration, the handler value is example.Hello::handleRequest.

To update the function's code, you create a deployment package, which is a .zip file archive that contains your function code. As your function development progresses, you will want to store your function code in source control, add libraries, and automate deployments. Start by creating a deployment package and updating your code at the command line.

The function runtime passes a context object to the handler, in addition to the invocation event. The context object contains additional information about the invocation, the function, and the execution environment. More information is available from environment variables.

Your Lambda function comes with a CloudWatch Logs log group. The function runtime sends details about each invocation to CloudWatch Logs. It relays any logs that your function outputs during invocation. If your function returns an error, Lambda formats the error and returns it to the invoker.