Java SDK

Updated at:

Integrate Feature Generator into your Java service to perform feature transformation. Supported platforms: linux-x86_64 and macosx-arm64.

Limitations

  • Supports linux-x86_64 and macosx-arm64.

Using the Java SDK

The following example uses a Maven project.

1. Download the Feature Generator SDK JAR file to a local path, for example, /path/to/feature_generator-${version}-${platform}.jar:

Platform

JAR package

linux-x86_64

fg-linux-x86_64.jar

macosx-arm64

fg-macosx-arm64.jar

Note: By default, Feature Generator uses std::hash for hash bucketing. The implementation of std::hash varies across C++ standard libraries on different platforms, which can lead to inconsistent bucketing results.

To ensure consistent bucketing results across platforms, set the environment variable USE_FARM_HASH_TO_BUCKETIZE=true. For more information, see Global configuration.

2. Install the JAR to your local repository using mvn install:install-file:

mvn install:install-file \
  -Dfile=/path/to/feature_generator-${version}-${platform}.jar \
  -DgroupId=com.aliyun.pai \
  -DartifactId=feature_generator \
  -Dversion=${version} \
  -Dclassifier=${platform} \
  -Dpackaging=jar

Replace ${version} with the actual version number and ${platform} with the platform name.

3. Add the dependency to your pom.xml file:

<dependencies>
<dependency>
    <groupId>com.aliyun.pai</groupId>
    <artifactId>feature_generator</artifactId>
    <version>${version}</version>
    <classifier>linux-x86_64</classifier>
</dependency>
</dependencies>

4. Create the fg.json file:

Example:

{
  "features": [
    {
      "feature_name": "query_word",
      "feature_type": "id_feature",
      "value_type": "String",
      "expression": "user:query_word",
      "default_value": "",
      "combiner": "mean",
      "need_prefix": false,
      "is_multi": true
    },
    {
      "feature_name": "query_match",
      "feature_type": "lookup_feature",
      "map": "user:query_token",
      "key": "item:title",
      "needDiscrete": false,
      "needKey": false,
      "default_value": "0",
      "combiner": "sum",
      "need_prefix": false,
      "value_type": "double"
    },
    {
      "feature_name": "goods_id",
      "feature_type": "id_feature",
      "value_type": "String",
      "expression": "item:goods_id",
      "default_value": "-1024",
      "combiner": "mean",
      "need_prefix": false,
      "value_dimension": 1
    },
    {
      "feature_name": "filter_type",
      "feature_type": "id_feature",
      "value_type": "String",
      "expression": "item:filter_type",
      "default_value": "-1024",
      "combiner": "mean",
      "need_prefix": false,
      "value_dimension": 1
    },
    {
      "feature_name": "day_h",
      "feature_type": "id_feature",
      "value_type": "int64",
      "expression": "user:day_h",
      "default_value": "0",
      "combiner": "mean",
      "need_prefix": false,
      "value_dimension": 1
    },
    {
      "feature_name": "week_day",
      "feature_type": "id_feature",
      "value_type": "int64",
      "expression": "user:week_day",
      "default_value": "0",
      "combiner": "mean",
      "need_prefix": false,
      "value_dimension": 1
    },
    {
      "feature_name": "city",
      "feature_type": "id_feature",
      "value_type": "String",
      "expression": "user:city",
      "default_value": "-1024",
      "combiner": "mean",
      "need_prefix": false,
      "value_dimension": 1
    },
    {
      "feature_name": "province",
      "feature_type": "id_feature",
      "value_type": "String",
      "expression": "user:province",
      "default_value": "-1024",
      "combiner": "mean",
      "need_prefix": false,
      "value_dimension": 1
    },
    {
      "feature_name": "country",
      "feature_type": "id_feature",
      "value_type": "String",
      "expression": "user:country",
      "default_value": "-1024",
      "combiner": "mean",
      "need_prefix": false,
      "value_dimension": 1
    },
    {
      "feature_name": "is_new_user",
      "feature_type": "id_feature",
      "value_type": "int64",
      "expression": "user:is_new_user",
      "default_value": "-1024",
      "combiner": "mean",
      "need_prefix": false,
      "value_dimension": 1
    },
    {
      "feature_name": "focus_author",
      "feature_type": "id_feature",
      "value_type": "String",
      "expression": "user:focus_author",
      "separator": ",",
      "default_value": "-1024",
      "combiner": "mean",
      "need_prefix": false,
      "is_multi": true
    },
    {
      "feature_name": "title",
      "feature_type": "id_feature",
      "value_type": "String",
      "expression": "item:title",
      "default_value": "-1024",
      "combiner": "mean",
      "need_prefix": false,
      "is_multi": true
    }
  ],
  "reserves": [
    "request_id",
    "user_id",
    "is_click",
    "is_pay"
  ]
}

5. The following example shows how to use the Java API:

package org.example;

import com.aliyun.pai.fg.*;
import java.net.URL;
import java.util.*;

public class Main {
    public static void main(String[] args) {
        String filePath = "/path/to/fg.json";
        FgHandler handler = new FgHandler(filePath, 4, false);

        List<String> outputs = new ArrayList<>();
        outputs.add("goods_id");
        outputs.add("is_new_user");
        outputs.add("day_h");
        outputs.add("query_match"); // Specify the output feature names.
        outputs.add("title");
        outputs.add("filter_type");
        outputs.add("city");
        outputs.add("province");
        outputs.add("country");
        outputs.add("focus_author");
        handler.setOutputs(outputs.toArray(new String[0]));

        List<String> expectGoods = Arrays.asList("218687106", "1142068348", "1142068347");
        VariantVectorMap inputs = new VariantVectorMap.Builder()
                .putOptionalString("goods_id", expectGoods)
                .putOptionalInt32("is_new_user", Arrays.asList(0, 1, 0))
                .putOptionalInt32("day_h", Arrays.asList(6, 8, 11))
                .putListString("title", Arrays.asList(
                        Arrays.asList("k2", "k3", "k5"),
                        Arrays.asList("k1", "k2", "k3"),
                        Arrays.asList("k2", "k4")))
                .putMapStringFloat("query_token", Arrays.asList(
                        new HashMap<String, Float>() {{
                            put("k2", 0.8f);
                            put("k3", 0.5f);
                        }},
                        new HashMap<String, Float>() {{
                            put("k1", 0.9f);
                            put("k4", 0.2f);
                        }},
                        new HashMap<String, Float>() {{
                            put("k1", 0.7f);
                            put("k2", 0.3f);
                            put("k4", 0.6f);
                        }}))
                .putOptionalString("filter_type", Arrays.asList(null, "f1", null))
                .putOptionalString("city", Arrays.asList("hangzhou"))
                .putOptionalString("province", Arrays.asList("zhejiang"))
                .putOptionalString("country", Arrays.asList("china"))
                .putOptionalString("focus_author", Arrays.asList("2255010511022,14164467", "10511022,24164467", "550105110,34164467"))
                .build();

        VariantVectorMap results = handler.Process(inputs);
        if (results == null || results.isNull()) {
            System.out.println("fg result is null");
            return;
        }
        inputs.close();  // Release native memory.

        System.out.println("result size=" + results.size());
        List<String> features = results.getKeys();
        System.out.println("result features=" + features);
        List<String> goodsIds = results.getList("goods_id");
        System.out.println("goods_ids=" + String.join(", ", goodsIds));

        List<List<String>> titles = results.getList("title");
        System.out.println("titles=" + titles);

        List<Long> dayHours = results.getList("day_h");
        System.out.println("day_h=" + dayHours);

        List<String> filters = results.getList("filter_type");
        System.out.println("filter_type=" + String.join(", ", filters));

        List<List<String>> focus = results.getList("focus_author");
        System.out.println("focus_author=" + focus);

        List<String> citys = results.getList("city");
        System.out.println("city=" + String.join(", ", citys));

        List<String> provinces = results.getList("province");
        System.out.println("provinces=" + String.join(", ", provinces));

        List<String> countrys = results.getList("country");
        System.out.println("country=" + String.join(", ", countrys));

        List<Long> isNewUsers = results.getList("is_new_user");
        System.out.println("is_new_user=" + isNewUsers);

        List<Double> queryMatch = results.getList("query_match");
        System.out.println("query_match=" + queryMatch);
        System.out.println("===========================================================");

        Set<String> itemInputs = handler.GetItemInputNames();
        System.out.println("item side inputs=" + itemInputs);

        Set<String> userInputs = handler.GetUserInputNames();
        System.out.println("user side inputs=" + userInputs);

        Set<String> ctxInputs = handler.GetContextInputNames();
        System.out.println("context side inputs=" + ctxInputs);

        Set<String> reserved = handler.GetReserveColumns();
        System.out.println("reserved columns =" + reserved);

        Set<String> qminputs = handler.GetFeatureInputs("query_match");
        System.out.println("inputs of query_match =" + qminputs);

        String defaultVal = handler.DefaultFeatureValue("query_match");
        System.out.println("default feature value of query_match =" + defaultVal);

        List<String> allFeatures = handler.GetAllFeatureNames();
        System.out.println("all feature names:" + allFeatures);

        Map<String, String> schema = handler.GetTableSchema();
        System.out.println("table schema:" + schema);

        results.close();  // Release native memory.
        handler.close();  // Release resources.
    }
}

SDK reference

FgHandler class

The FgHandler class processes input features and generates results based on a JSON configuration.

Key capabilities:

  • Initializes the feature processor from a configuration. You can specify the thread count and whether to perform only the bucketize operation.

  • Processes input features: Process(VariantVectorMap inputs) -> VariantVectorMap

  • Sets the output features: setOutputs(...)

  • Queries input, output, and feature metadata such as feature names, schema, default values, and dimensions.

  • Explicitly releases native resources: close() (must be called).

Quick start

Initialization

Four constructors are available (all call the native allocate function):

// 1. Configuration only
FgHandler handler = new FgHandler(configJsonOrPath);
// 2. Configuration + thread count
FgHandler handler = new FgHandler(configJsonOrPath, threadNum);
// 3. Configuration + thread count + bucketize-only flag
FgHandler handler = new FgHandler(configJsonOrPath, threadNum, bucketizeOnly);
// 4. Configuration + thread count + bucketize-only flag + configuration path flag
FgHandler handler = new FgHandler(configJsonOrPath, threadNum, bucketizeOnly, isCfgPath);

Parameters:

  • config_json: The configuration content (a JSON string) or the path to a configuration file. This is determined by the is_cfg_path flag.

  • thread_num: The number of internal processing threads for the native layer (size_t).

  • bucketize_only: Specifies whether to perform only the bucketize operation. You can check this setting using the IsOnlyBucketize() method.

  • is_cfg_path: If set to true, config_json is treated as a file path; if set to false, it is treated as a JSON string.

Setting output features

You can set the output features in two ways:

handler.setOutputs("feature_a", "feature_b");
// Or use a String[] array as a parameter.
List<String> outputs = new ArrayList<>();
outputs.add("goods_id");
outputs.add("is_new_user");
outputs.add("title");
outputs.add("city");
outputs.add("province");
outputs.add("country");
handler.setOutputs(outputs.toArray(new String[0]));

Alternatively, you can use the low-level interface:

StrVector outs = new StrVector();
outs.push_back("feature_a");
outs.push_back("feature_b");
handler.setOutputs(outs);

If you do not set any output features, the handler returns all features defined in the configuration by default.

Processing inputs

VariantVectorMap inputs = new VariantVectorMap();
// TODO: Fill inputs based on the VariantVectorMap API.
VariantVectorMap outputs = handler.Process(inputs);
if (outputs == null || outputs.isNull()) {
   System.out.println("fg output is null");
   inputs.close();
   return;
}
// TODO: Read results from outputs.

FgHandler.Process(inputs) performs batch processing on samples. Both the input and output are of the VariantVectorMap type.

  • VariantVectorMap: A Map<String, VariantVector> where the key is a field or feature name.

  • VariantVector: A container for batch data that uses columnar storage (a column vector). It supports various nested structures:

    • Optional scalar: List<T> (length = batch size; can contain null values).

    • Sequence: List<List<T>> (outer list length = batch size).

    • Map feature: List<Map<K,V>> (outer list length = batch size).

    • Matrix feature: List<List<List<T>>> (outer list length = batch size, with one 2D matrix per sample).

  • The Process method may return null if feature transformation fails. You must always check the result before using it.

Input and output data structures

VariantVectorMap (input/output container)

Basic API

  • Construction:

    • new VariantVectorMap()

    • VariantVectorMap.fromJavaMap(Map<String, VariantVector>)

    • new VariantVectorMap.Builder()...build()

  • Write Operations:

    • put(String key, VariantVector value)

    • putAll(Map<String, VariantVector>)

  • Read Operations:

    • VariantVector get(String key)

    • boolean contains(String key)

    • List<String> getKeys()

    • long size()

    • Map<String, VariantVector> toJavaMap() (converts to a Java Map)

  • Resource Release:

    • clear(): Clears all elements.

    • close(): Releases native memory. You must call this method to prevent a memory leak.

Build inputs with Builder (recommended)

The VariantVectorMap.Builder class provides multiple putXXX methods.

Optional scalar (for one batch):

VariantVectorMap inputs = new VariantVectorMap.Builder()
    .putOptionalInt64("user_id", Arrays.asList(1001L, 1002L))
    .putOptionalString("item_id", Arrays.asList("i1", "i2"))
    .putOptionalDouble("score", Arrays.asList(0.1, null)) // null is supported.
    .build();

Single value (batch size = 1):

VariantVectorMap inputs = new VariantVectorMap.Builder()
    .putSingleOptionalInt64("user_id", 1001L)
    .putSingleOptionalString("item_id", "i1")
    .build();

Sequence (List type, one list per sample in a batch):

VariantVectorMap inputs = new VariantVectorMap.Builder()
    .putListInt64("clicked_item_ids",
        Arrays.asList(
            Arrays.asList(11L, 12L),
            Arrays.asList(21L)
        )
    )
    .build();

Map feature (one map per sample in a batch):

VariantVectorMap inputs = new VariantVectorMap.Builder()
    .putMapStringFloat("user_dense",
        Arrays.asList(
            Map.of("age", 18.0f, "lvl", 3.0f),
            Map.of("age", 25.0f)
        )
    )
    .build();

Matrix feature (one 2D matrix per sample):

VariantVectorMap inputs = new VariantVectorMap.Builder()
    .putMatrixFloat("image_emb",
        Arrays.asList(
            Arrays.asList( // sample1 matrix
                Arrays.asList(0.1f, 0.2f),
                Arrays.asList(0.3f, 0.4f)
            ),
            Arrays.asList( // sample2 matrix
                Arrays.asList(1.0f, 2.0f)
            )
        )
    )
    .build();

getList: Type-dispatched reads (common for outputs)

VariantVectorMap.getList(key) automatically selects the registered TypeReference for conversion based on the type returned by VariantVector.getType().

Example: Read a feature named feature_x of the OPTIONAL_FLOAT type.

List<Float> xs = out.getList("feature_x");   // Returns a List<Float>.

Read LIST_INT64 (returns List<List<Long>>):

List<List<Long>> seq = out.getList("seq_feature");

Note:

  • The return type of getList is <T> List<T> and cannot be strongly constrained at compile time. A type mismatch throws an IllegalArgumentException("Type mismatch...") at runtime.

  • TYPE_REGISTRY has pre-registered mappings for all defined type constants to TypeReference.

We recommend obtaining the output table schema to determine the correct return type for getList.

Map<String, String> schema = handler.GetTableSchema();
System.out.println("table schema:" + schema);

VariantVector (column vector and type system)

A VariantVector object represents single-column data. You must set its type and organize the internal data accordingly.

Supported types

  • Optional (allows null; outer layer is the batch):

    • OPTIONAL_STRING / INT32 / INT64 / FLOAT / DOUBLE

    • Java representation: List<T> (length = batch size; elements can be null).

  • Sequence (a list per sample):

    • LIST_STRING / INT32 / INT64 / FLOAT / DOUBLE

    • Java representation: List<List<T>> (outer list length = batch size).

  • Map feature (one map per sample):

    • MAP_STRING_*: List<Map<String, V>>

    • MAP_INT32_*: List<Map<Integer, V>>

    • MAP_INT64_*: List<Map<Long, V>>

  • Matrix feature (one 2D matrix per sample):

    • MATRIX_FLOAT / MATRIX_INT64 / MATRIX_STRING

    • Java representation: List<List<List<T>>>

Construction: Static fromXXX methods (recommended)

Instead of writing low-level Builder(type).withXXXData() calls, use the static methods directly:

  • VariantVector.fromOptionalInt64(List<Long> values)

  • VariantVector.fromListFloat(List<List<Float>> values)

  • VariantVector.fromMapStringInt32(List<Map<String,Integer>> maps)

  • VariantVector.fromMatrixFloat(List<List<List<Float>>> matrices) etc.

Example (manual construction before adding to a map):

VariantVector userIds = VariantVector.fromOptionalInt64(Arrays.asList(1L, 2L, null));
VariantVectorMap inputs = new VariantVectorMap();
inputs.put("user_id", userIds);

Objects constructed in this way have their own native memory. After use, you must call close() to release it.

Borrowed memory mode objects:

VariantVectorMap results;
// build results
VariantVector v = results.get("goods_id");

This object is a view whose underlying memory is shared with the VariantVectorMap object. After the VariantVectorMap is released, this view becomes a dangling reference and can no longer be used.

You do not need to call close() on a borrowed VariantVector object after you are finished using it. Do not store the object separately for an extended period because its lifecycle depends on the VariantVectorMap object to which it belongs.

Read operations: toXXXList

After obtaining a VariantVector object, call the corresponding conversion method based on its type:

VariantVector vv = out.get("feature_x");
if (vv.getType() == VariantVector.OPTIONAL_DOUBLE) {
    List<Double> vals = vv.toOptionalDoubleList();
}

Alternatively, use VariantVectorMap.getList(key) for automatic dispatch (see the previous section).

Helper methods: size / isEmpty / totalElementCount

  • vv.size():

    • Optional: Returns the batch size (length of nullFlags).

    • For other types: Returns sizes[0] (outer element count, which usually equals the batch size).

  • vv.isEmpty(): Checks if the underlying data is empty based on the type.

  • vv.totalElementCount(): Returns the total number of elements after expanding nested lists, maps, or matrices. Useful for debugging and verification.

Metadata query API

Use these methods to query configuration content and feature dependencies.

Querying input field collections

Set<String> itemInputs = handler.GetItemInputNames();
Set<String> userInputs = handler.GetUserInputNames();
Set<String> ctxInputs  = handler.GetContextInputNames();

Querying feature names, reserved columns, and special collections

List<String> allFeatures = handler.GetAllFeatureNames();
Set<String> reserveCols  = handler.GetReserveColumns();
Set<String> userSide     = handler.GetUserSideFeatures();
Set<String> seqFeatures  = handler.GetSequenceFeatures();

Querying feature dependencies, default values, dimensions, and bucketizers

Set<String> deps = handler.GetFeatureInputs("feature_x");
String defaultVal = handler.DefaultFeatureValue("feature_x");
long defaultBucket = handler.DefaultBucketizedFeatureValue("feature_x");
long dim = handler.GetFeatureValueDim("feature_x");
boolean hasBucketizer = handler.HasBucketizer("feature_x");
boolean onlyBucketize = handler.IsOnlyBucketize();

Use cases:

  • Generate input preparation logic by determining which raw inputs a feature needs.

  • Fill or validate missing inputs using default values.

  • Ensure the output meets the fixed dimension (dim) required by a downstream model.

  • Decide whether additional bucketize processing is needed (hasBucketizer/onlyBucketize).

Querying the output table schema

Usage:

Map<String, String> schema = handler.GetTableSchema();
String type = schema.get("feature_x");

Resource release

FgHandler holds a pointer to a native object. You must release it when it is no longer needed to prevent a memory leak.

It is a heavyweight object. Typically, you should:

  • Initialize it once.

  • Reuse it for multiple operations.

  • Call close() when the service exits.

Correct usage:

  • Do not create a new FgHandler() for each request.

  • Use one long-lived, reusable handler for each configuration.

When you are finished using FgHandler, call close() to release its resources. This method has the following properties:

  • Thread-safe: It is synchronized.

  • Idempotent: Calling it multiple times does not cause repeated releases.

After calling close(), do not call any other native method (including Process and query methods), as this may cause a crash (use-after-free).

FgHandler handler = new FgHandler(cfg, 4);
try {
    ...
} finally {
    handler.close();
}

During debugging, you can use the try-with-resources statement:

try (FgHandler handler = new FgHandler(cfg, 4)) {
    handler.setOutputs("f1", "f2");
    VariantVectorMap out = handler.Process(in);
}

In a production environment, do not frequently create identical FgHandler objects.

When using FgHandler within a service, do not create a new FgHandler object for each request. Initialization overhead is high, and frequent creation degrades service performance.

Create a global instance in your service's initialization function and call close() in the exit function. Follow the same pattern for multiple FgHandler objects.


Recommended request processing patterns:

Pattern A: Synchronous request

public Result handle(Request req, FgHandler handler) {
    try (VariantVectorMap inputs = buildInputs(req);
         VariantVectorMap results = handler.Process(inputs)) {
        Result r = new Result();
        r.goodsIds = results.get("goods_id").toOptionalStringList();
        r.dayHs = results.get("day_h").toOptionalInt32List();
        r.titles = results.get("title").toListStringList();
        return r;
    }
}

Features:

  • Clear scope for native resources.

  • Resources are released upon request completion.

  • Less prone to OOM errors.

Pattern B: Service-level singleton handler

public class FgService implements AutoCloseable {
    private final FgHandler handler;
    public FgService(String configPath) {
        this.handler = new FgHandler(configPath, 4, false, true);
    }
    public Result process(Request req) {
        try (VariantVectorMap inputs = buildInputs(req);
             VariantVectorMap results = handler.Process(inputs)) {
            return decode(results);
        }
    }
    @Override
    public void close() {
        handler.close();
    }
}

This is the recommended approach for production environments.

Common usage examples

Prepare input fields based on the configuration before processing:

FgHandler handler = new FgHandler(cfgJson, 8, false, false);
try {
    // 1. Set the required outputs.
    handler.setOutputs("feature_a", "feature_b");
    // 2. Determine which inputs to prepare.
    Set<String> itemInputs = handler.GetItemInputNames();
    Set<String> userInputs = handler.GetUserInputNames();
    Set<String> ctxInputs  = handler.GetContextInputNames();
    // 3. Construct inputs (this is an example and depends on the VariantVectorMap API).
    VariantVectorMap inputs = new VariantVectorMap();
    // inputs.put("user_id", ...)
    // inputs.put("item_id", ...)
    // inputs.put("ts", ...)
    VariantVectorMap outputs = handler.Process(inputs);
    inputs.close();
    // Read outputs...
    outputs.close();
} finally {
    handler.close();
}

Perform only a bucketize operation:

FgHandler handler = new FgHandler(cfgJson, 4, true, false);
try {
    if (!handler.IsOnlyBucketize()) {
        // Provide a warning if the configuration or constructor parameters do not match.
    }
    ...
} finally {
    handler.close();
}

Safe standard usage:

try (FgHandler handler = new FgHandler(configPath, 4, false, true)) {
    handler.setOutputs("goods_id", "day_h", "title");
    try (VariantVectorMap inputs = new VariantVectorMap.Builder()
            .putOptionalString("goods_id", Arrays.asList("1", "2"))
            .putOptionalInt32("day_h", Arrays.asList(6, 8))
            .putListString("title", Arrays.asList(
                    Arrays.asList("a", "b"),
                    Arrays.asList("c", "d")))
            .build();
         VariantVectorMap results = handler.Process(inputs)) {
        List<String> goodsIds = results.get("goods_id").toOptionalStringList();
        List<Integer> dayHs = results.get("day_h").toOptionalInt32List();
        List<List<String>> titles = results.get("title").toListStringList();
        // Use outputs immediately. Do not hold references to `results` or borrowed `VariantVector` objects for long periods.
    }
}

OOM error patterns

1. Not closing VariantVectorMap

Incorrect example:

for (...) {
    VariantVectorMap inputs = new VariantVectorMap.Builder()...build();
    VariantVectorMap results = handler.Process(inputs);
    // Not closed.
}

This leads to the following issues:

  • Java objects are eventually garbage-collected.

  • Native memory is not released promptly.

  • Under high QPS, a large number of unreleased objects accumulate, eventually causing an OOM error or a spike in the native RSS.

Correct example:

for (...) {
    try (VariantVectorMap inputs = new VariantVectorMap.Builder()...build();
         VariantVectorMap results = handler.Process(inputs)) {
        ...
    }
}

A try-with-resources statement automatically releases these resources.

2. New FgHandler per request

Incorrect example:

for (...) {
    FgHandler handler = new FgHandler(configPath, 4, false, true);
    ...
}

This pattern is expensive because it:

  • Repeatedly loads the configuration.

  • Re-initializes thread pools and internal structures.

  • Repeatedly allocates native resources.

Correct example:

FgHandler handler = new FgHandler(configPath, 4, false, true);
try {
    for (...) {
        ...
    }
} finally {
    handler.close();
}

3. Cache the results.get(key) return value

Incorrect example:

VariantVector v = results.get("goods_id");
cache.add(v);   // Incorrect

This is problematic because the returned object is a borrowed reference:

  • The object becomes invalid after results.close() is called.

  • If you do not call results.close(), the native memory is never released.

Correct approaches:

Decode the data into a regular Java object immediately:

List<String> goodsIds = results.get("goods_id").toOptionalStringList();
cache.add(goodsIds);

Alternatively, if you must save the native object, use getCopy() and ensure that you close it when it is no longer needed:

VariantVector copy = results.getCopy("goods_id");
try {
    ...
} finally {
    copy.close();
}

We do not recommend caching a native copy unless it is absolutely necessary.

4. Values are not released after extensive use of toJavaMap()

The toJavaMap() method returns an owned copy that can create many native objects.

Incorrect example:

Map<String, VariantVector> map = results.toJavaMap();
// The VariantVector values in the map are not closed.

Correct approaches:

  • Avoid using this method unless it is necessary.

  • We recommend reading fields directly into Java objects when possible.

  • If you must use this method, ensure you close all created objects:

Map<String, VariantVector> map = results.toJavaMap();
try {
    ...
} finally {
    for (VariantVector v : map.values()) {
        if (v != null) v.close();
    }
}

5. Builder-generated intermediate VariantVector objects persist in a Java Map

For example:

VariantVectorMap.Builder builder = new VariantVectorMap.Builder();
builder.putOptionalString(...);
builder.putOptionalInt32(...);
// The builder and its data exist for a long time.

A Builder internally holds multiple VariantVector objects, which are owned native objects.

If a Builder object persists for a long time, it pins native memory.

Correct usage:

  • Keep the lifecycle of a Builder as short as possible. Use it only to construct the inputs for a single request.