Building Lambda functions with Java - AWS Lambda

Building Lambda functions with Java

You can run Java code in AWS Lambda. Lambda providesruntimesfor 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 theLambda console.

  2. ChooseCreate function.

  3. Configure the following settings:

    • Function name:Enter a name for the function.

    • Runtime:ChooseJava 21.

  4. ChooseCreate function.

  5. To configure a test event, chooseTest.

  6. ForEvent name,entertest.

  7. ChooseSave changes.

  8. To invoke the function, chooseTest.

The console creates a Lambda function with a handler class namedHello. 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 thesample applicationsavailable in this guide's GitHub repository.

TheHelloclass has a function namedhandleRequestthat takes an event object and a context object. This is thehandler functionthat 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 isexample.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 bycreating a deployment packageand updating your code at the command line.

The function runtime passes a context object to the handler, in addition to the invocation event. Thecontext objectcontains 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 anylogs that your function outputsduring invocation. If your function returns an error, Lambda formats the error and returns it to the invoker.