Use Java SDK to start a Spark task

Updated at:

Submit a Spark job to E-MapReduce (EMR) Serverless Spark programmatically using the EMR Serverless Spark SDK for Java. The SDK call returns a job run ID that you can use to track execution.

Prerequisites

Before you begin, ensure that you have:

Using environment variables to pass credentials is safer than hardcoding them in your source code. For production workloads, use Security Token Service (STS) for short-lived, automatically rotated credentials.

Add the SDK dependency

Add the following dependency to your pom.xml to import the EMR Serverless Spark SDK:

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>emr_serverless_spark20230808</artifactId>
    <version>1.0.0</version>
</dependency>

Replace version with the latest release. Check the Maven Central repository for the current version.

Submit a Spark job

The following example submits a SparkPi job to EMR Serverless Spark and prints the returned job run ID.

Each request calls startJobRunWithOptions with your workspace ID, a StartJobRunRequest containing the job configuration, and credentials loaded from environment variables.

import java.util.Arrays;

import com.aliyun.emr_serverless_spark20230808.Client;
import com.aliyun.emr_serverless_spark20230808.models.StartJobRunResponse;
import com.aliyun.emr_serverless_spark20230808.models.Tag;
import com.aliyun.tea.TeaException;

public class AliyunServerlessSparkTaskExample {
    public static void main(String[] args) throws Exception {
        com.aliyun.emr_serverless_spark20230808.Client client = AliyunServerlessSparkTaskExample.createClient();

        // Build the job run request
        com.aliyun.emr_serverless_spark20230808.models.StartJobRunRequest startJobRunRequest =
            new com.aliyun.emr_serverless_spark20230808.models.StartJobRunRequest();
        startJobRunRequest.setRegionId("cn-hangzhou");
        startJobRunRequest.setResourceQueueId("root_queue");
        startJobRunRequest.setCodeType("JAR");
        startJobRunRequest.setName("spark-task");
        startJobRunRequest.setReleaseVersion("esr-2.1-native (Spark 3.3.1, Scala 2.12, Native Runtime)");

        // Attach tags to organize and identify job runs
        Tag envTag = new Tag();
        envTag.setKey("environment");
        envTag.setValue("production");
        Tag workflowTag = new Tag();
        workflowTag.setKey("workflow");
        workflowTag.setValue("true");
        startJobRunRequest.setTags(Arrays.asList(envTag, workflowTag));

        // Configure the Spark job entry point and resource parameters
        com.aliyun.emr_serverless_spark20230808.models.JobDriver.JobDriverSparkSubmit jobDriverSparkSubmit =
            new com.aliyun.emr_serverless_spark20230808.models.JobDriver.JobDriverSparkSubmit()
                .setEntryPoint("oss://<YourBucket>/spark-resource/examples/jars/spark-examples_2.12-3.3.1.jar")
                .setEntryPointArguments(java.util.Arrays.asList("1"))
                .setSparkSubmitParameters(
                    "--class org.apache.spark.examples.SparkPi " +
                    "--conf spark.executor.cores=4 " +
                    "--conf spark.executor.memory=20g " +
                    "--conf spark.driver.cores=4 " +
                    "--conf spark.driver.memory=8g " +
                    "--conf spark.executor.instances=1"
                );
        com.aliyun.emr_serverless_spark20230808.models.JobDriver jobDriver =
            new com.aliyun.emr_serverless_spark20230808.models.JobDriver()
                .setSparkSubmit(jobDriverSparkSubmit);
        startJobRunRequest.setJobDriver(jobDriver);

        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        java.util.Map<String, String> headers = new java.util.HashMap<>();

        try {
            // Submit the job run; replace the workspace ID with your own
            StartJobRunResponse startJobRunResponse = client.startJobRunWithOptions(
                "w-f7b841e8c732****", startJobRunRequest, headers, runtime
            );
            System.out.println(startJobRunResponse.getBody().getJobRunId());
        } catch (TeaException error) {
            System.out.println(error.getMessage());
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            System.out.println(error.getMessage());
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
    }

    // Initializes the client using credentials from environment variables.
    // Replace the region in the endpoint with the region where your workspace is deployed.
    public static Client createClient() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
            .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
            .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        config.endpoint = "emr-serverless-spark.cn-hangzhou.aliyuncs.com";
        return new com.aliyun.emr_serverless_spark20230808.Client(config);
    }
}

Replace the following placeholders before running the example:

PlaceholderDescriptionExample
<YourBucket>The OSS bucket where your JAR file is storedmy-emr-bucket
w-f7b841e8c732****Your EMR Serverless Spark workspace IDw-abc123def456****
cn-hangzhouThe region where your workspace is deployedcn-beijing

Key parameters

ParameterDescription
regionIdThe region where the workspace is deployed
resourceQueueIdThe resource queue to run the job. Use root_queue for the default queue
codeTypeThe job code type. JAR for packaged Java or Scala applications
nameA descriptive name for the job run
releaseVersionThe EMR Serverless Spark runtime version, including the Spark and Scala versions
entryPointThe OSS path to the JAR file
entryPointArgumentsArguments passed to the main class
sparkSubmitParametersSpark configuration flags, including driver and executor resource allocation