JDBC Row Sets: CachedRowSet, WebRowSet, FilteredRowSet and JoinRowSet
Work with data after closing the connection: RowSetProvider and RowSetFactory, populating a CachedRowSet, editing offline and writing back with acceptChanges, conflict handling with SyncResolver, paging, JdbcRowSet, WebRowSet XML, filtering, joining and listeners.
kvi5hnuCode Sprout team member9 min readOn this page
A scrollable result set (article 62) keeps its connection busy for as long as you use it. If a user browses query results for ten minutes, that's ten minutes of a scarce database connection, possibly with locks and an open transaction. A row set solves this. It extends ResultSet, so you read it with the same methods, but it can hold its data on its own: query, copy the rows, close the connection, and then browse, edit, send, save or filter the rows offline. When you're done editing, the row set reconnects briefly to write the changes back.
Row sets have been part of Java since Java 5, in the package javax.sql.rowset (module java.sql.rowset). Today they appear mostly in older desktop and enterprise code. New applications usually map rows to records or objects (article 66) and send JSON rather than row sets. But the API is still part of the JDK, and the ideas, disconnected data and optimistic write-back, show up in every persistence framework.
The kinds of row sets
RowSet extends ResultSet. The subinterfaces in javax.sql.rowset are:
| Interface | Purpose |
|---|---|
JdbcRowSet | a connected wrapper around a result set that adds the row set API, such as connection settings, setCommand and listeners. By default it is scrollable and updatable |
CachedRowSet | a disconnected copy of the rows that you can edit and later synchronize with the database |
WebRowSet | a CachedRowSet that can write itself to XML and read itself back |
FilteredRowSet | a WebRowSet that shows only rows accepted by a filter |
JoinRowSet | a WebRowSet that joins several row sets on matching columns, without the database |
You obtain implementations from a factory:
RowSetFactory factory = RowSetProvider.newFactory();
CachedRowSet crs = factory.createCachedRowSet();
RowSetProvider.newFactory() returns the JDK's built-in implementation unless a different one is configured (through the system property javax.sql.rowset.RowSetFactory or the ServiceLoader).
Cached row sets
Filling a cached row set
There are two ways. You can copy an existing result set, then close the connection:
try (Connection conn = dataSource.getConnection();
Statement stat = conn.createStatement();
ResultSet rs = stat.executeQuery("SELECT id, name, price FROM products")) {
crs.populate(rs);
}
// the connection is closed, crs still has all rows
Or you can give the row set a command and let it run the query itself. execute(conn) uses the given connection, and the no-argument execute() opens its own from setUrl/setUsername/setPassword or setDataSourceName:
crs.setCommand("SELECT id, name, price FROM products WHERE price < ?");
crs.setBigDecimal(1, new BigDecimal("100"));
crs.execute(conn);
All rows go into memory. For large results, set a page size first. setPageSize(20) makes execute load only the first 20 rows, and nextPage() and previousPage() load the neighbors.
Writing changes back
You edit a cached row set like an updatable result set: updateXxx plus updateRow, moveToInsertRow and insertRow, deleteRow. Nothing reaches the database yet. The row set remembers the original values along with the changes. acceptChanges(conn), or acceptChanges() with stored connection settings, connects and writes all changes in a transaction. (With the JDK implementation, it commits for you.)
The row set needs to know which table to write to and how to identify rows. When it ran its own command, it can usually work that out. After populate, call setTableName("products") and setKeyColumns(new int[] { 1 }).
Conflicts
Between reading and writing back, someone else may have changed the same rows. The JDK's default synchronization provider uses optimistic concurrency: for each changed row, it checks that the database still holds the original values. If any row differs, it writes nothing and throws a SyncProviderException. Its getSyncResolver() lists each conflict, with the row, the value currently in the database (getConflictValue) and the kind of conflict (UPDATE_ROW_CONFLICT, DELETE_ROW_CONFLICT, INSERT_ROW_CONFLICT). You can decide per conflict which value wins with setResolvedValue and then try again. Other providers can use other strategies.
Trying it with H2
This program fills a cached row set, closes the connection, changes a price, inserts a row and writes the changes back. It then edits a row that another connection changes in the meantime, which produces a conflict. Finally it pages through a query result three rows at a time and uses a JdbcRowSet:
import java.math.BigDecimal;
import java.sql.*;
import javax.sql.rowset.*;
import javax.sql.rowset.spi.*;
public class RowSets {
static final String URL = "jdbc:h2:mem:shop;DB_CLOSE_DELAY=-1";
public static void main(String[] args) throws SQLException {
try (Connection conn = DriverManager.getConnection(URL); Statement stat = conn.createStatement()) {
stat.executeUpdate("CREATE TABLE products (id INT PRIMARY KEY, name VARCHAR(40), price DECIMAL(8,2))");
stat.executeUpdate("""
INSERT INTO products VALUES (1, 'Hammer', 12.50), (2, 'Oak shelf', 89.90), (3, 'Pine stool', 35.00),
(4, 'Desk lamp', 42.00), (5, 'Saw', 19.00), (6, 'Tape measure', 7.25), (7, 'Chisel', 15.80)""");
}
RowSetFactory factory = RowSetProvider.newFactory();
System.out.println("--- populate, disconnect, edit, write back ---");
CachedRowSet crs = factory.createCachedRowSet();
try (Connection conn = DriverManager.getConnection(URL);
Statement stat = conn.createStatement();
ResultSet rs = stat.executeQuery("SELECT id, name, price FROM products WHERE price > 30 ORDER BY id")) {
crs.populate(rs);
} // connection closed; the rows stay
crs.setTableName("products"); // needed: populate doesn't know the table
crs.setKeyColumns(new int[] { 1 });
while (crs.next()) {
System.out.println(" " + crs.getInt("id") + " " + crs.getString("name") + " " + crs.getBigDecimal("price"));
if (crs.getString("name").equals("Desk lamp")) {
crs.updateBigDecimal("price", new BigDecimal("39.00"));
crs.updateRow();
}
}
crs.moveToInsertRow();
crs.updateInt("id", 8);
crs.updateString("name", "Spirit level");
crs.updateBigDecimal("price", new BigDecimal("31.00"));
crs.insertRow();
crs.moveToCurrentRow();
try (Connection conn = DriverManager.getConnection(URL)) {
conn.setAutoCommit(false); // acceptChanges commits itself
crs.acceptChanges(conn);
}
print("database after acceptChanges", "SELECT id, name, price FROM products WHERE price > 30 ORDER BY id");
System.out.println("--- a conflicting change ---");
crs.beforeFirst();
while (crs.next()) {
if (crs.getString("name").equals("Oak shelf")) {
crs.updateBigDecimal("price", new BigDecimal("79.00"));
crs.updateRow();
}
}
try (Connection other = DriverManager.getConnection(URL); Statement stat = other.createStatement()) {
stat.executeUpdate("UPDATE products SET price = 95.00 WHERE id = 2"); // someone else was faster
}
try (Connection conn = DriverManager.getConnection(URL)) {
conn.setAutoCommit(false);
crs.acceptChanges(conn);
System.out.println("written");
} catch (SyncProviderException e) {
SyncResolver resolver = e.getSyncResolver();
while (resolver.nextConflict()) {
System.out.println("conflict in row " + resolver.getRow() + ": database has price "
+ resolver.getConflictValue("price") + ", status " + (resolver.getStatus() == SyncResolver.UPDATE_ROW_CONFLICT ? "UPDATE_ROW_CONFLICT" : resolver.getStatus()));
}
}
print("database after the conflict", "SELECT id, name, price FROM products WHERE id = 2");
System.out.println("--- command, parameters and pages ---");
CachedRowSet paged = factory.createCachedRowSet();
paged.setCommand("SELECT name FROM products WHERE price < ? ORDER BY name");
paged.setBigDecimal(1, new BigDecimal("100"));
paged.setPageSize(3);
try (Connection conn = DriverManager.getConnection(URL)) {
paged.execute(conn);
int page = 1;
do {
StringBuilder sb = new StringBuilder(" page " + page++ + ":");
while (paged.next()) sb.append(" ").append(paged.getString(1));
System.out.println(sb);
} while (paged.nextPage());
}
System.out.println("--- JdbcRowSet: a connected wrapper ---");
try (JdbcRowSet jrs = factory.createJdbcRowSet()) {
jrs.setUrl(URL);
jrs.setCommand("SELECT name FROM products WHERE id = ?");
jrs.setInt(1, 5);
jrs.execute();
while (jrs.next()) System.out.println(" " + jrs.getString(1));
}
}
static void print(String title, String sql) throws SQLException {
System.out.println(title + ":");
try (Connection conn = DriverManager.getConnection(URL); Statement stat = conn.createStatement(); ResultSet rs = stat.executeQuery(sql)) {
while (rs.next()) System.out.println(" " + rs.getInt(1) + " " + rs.getString(2) + " " + rs.getBigDecimal(3));
}
}
}
Output with H2 2.3:
--- populate, disconnect, edit, write back ---
2 Oak shelf 89.90
3 Pine stool 35.00
4 Desk lamp 42.00
database after acceptChanges:
2 Oak shelf 89.90
3 Pine stool 35.00
4 Desk lamp 39.00
8 Spirit level 31.00
--- a conflicting change ---
conflict in row 1: database has price 95.00, status UPDATE_ROW_CONFLICT
database after the conflict:
2 Oak shelf 95.00
--- command, parameters and pages ---
page 1: Chisel Desk lamp Hammer
page 2: Oak shelf Pine stool Saw
page 3: Spirit level Tape measure
--- JdbcRowSet: a connected wrapper ---
Saw
The conflicting edit was rejected, and the price the other connection wrote, 95.00, stays.
Web, filtered and join row sets
WebRowSetwrites its complete state to XML withwriteXml(writer)and restores it withreadXml(reader). That includes the properties (command, table name, settings), the column metadata and the data, with original and changed values, so pending changes survive the trip. The format is defined by an XML schema in the JDK. It was designed for passing data between tiers of web applications. JSON-based APIs have replaced that use.FilteredRowSettakes ajavax.sql.rowset.Predicate(not thejava.util.functionone) throughsetFilter. Itsevaluate(RowSet)method decides which rows are visible, and theevaluate(value, column)methods decide which values may be inserted or updated. That's a lightweightWHEREclause applied in memory.setFilter(null)shows all rows again.JoinRowSetcombines row sets that are already in memory, possibly from different databases, on a match column:addRowSet(rowSet, "SUPPLIER")for each participant. The JDK implementation supports inner joins.
Listeners and serialization
A RowSetListener is notified when the cursor moves (cursorMoved), a row changes (rowChanged), or the whole row set is refilled (rowSetChanged). That was intended for keeping user interface tables in sync.
Cached row sets are Serializable, so you can send them over RMI or store them. Registered listeners are serialized with the row set, so remove them first. And as with all Java serialization (articles 32 to 35), never deserialize row sets from untrusted sources.
The program
The runnable demo fills row sets from arrays instead of a database, using RowSetMetaDataImpl for the column definitions and setOriginalRow() to make the rows look freshly loaded. A cached row set reports an update to a listener and survives serialization together with its pending change. A filtered row set shows only prices from 15 to 50 and refuses an insert that its filter rejects. A join row set combines products with suppliers on the SUPPLIER column, which drops the supplier without products and the product without a matching supplier. Finally, a web row set with one changed row is written to XML (a current row and a modified row) and read back.
import java.io.*;
import java.math.BigDecimal;
import java.sql.*;
import java.util.*;
import javax.sql.RowSet;
import javax.sql.RowSetEvent;
import javax.sql.RowSetListener;
import javax.sql.RowSetMetaData;
import javax.sql.rowset.*;
public class Solution {
static final RowSetFactory FACTORY;
static {
try { FACTORY = RowSetProvider.newFactory(); }
catch (SQLException e) { throw new ExceptionInInitializerError(e); }
}
// Fills a row set of the requested kind with rows given as arrays (stand-in for a database query)
static <T extends CachedRowSet> T fill(T rs, String table, String[] columns, int[] types, Object[][] rows) throws SQLException {
RowSetMetaData meta = new RowSetMetaDataImpl();
meta.setColumnCount(columns.length);
for (int i = 0; i < columns.length; i++) {
meta.setColumnName(i + 1, columns[i]);
meta.setColumnLabel(i + 1, columns[i]);
meta.setColumnType(i + 1, types[i]);
meta.setTableName(i + 1, table);
}
rs.setMetaData(meta);
rs.setTableName(table);
for (Object[] row : rows) {
rs.moveToInsertRow();
for (int i = 0; i < row.length; i++) rs.updateObject(i + 1, row[i]);
rs.insertRow();
}
rs.moveToCurrentRow();
rs.beforeFirst();
while (rs.next()) rs.setOriginalRow(); // as if just loaded
rs.beforeFirst();
return rs;
}
static final String[] PRODUCT_COLUMNS = { "ID", "NAME", "SUPPLIER", "PRICE" };
static final int[] PRODUCT_TYPES = { Types.INTEGER, Types.VARCHAR, Types.VARCHAR, Types.DECIMAL };
static final Object[][] PRODUCTS = {
{ 1, "Hammer", "ACME", new BigDecimal("12.50") }, { 2, "Oak shelf", "NORD", new BigDecimal("89.90") },
{ 3, "Pine stool", "NORD", new BigDecimal("35.00") }, { 4, "Desk lamp", "SOLA", new BigDecimal("42.00") },
{ 5, "Saw", "ACME", new BigDecimal("19.00") } };
// A FilteredRowSet uses a Predicate (javax.sql.rowset.Predicate, not java.util.function.Predicate)
static class PriceRange implements javax.sql.rowset.Predicate {
private final BigDecimal low, high;
PriceRange(String low, String high) { this.low = new BigDecimal(low); this.high = new BigDecimal(high); }
private boolean inRange(Object value) {
return value instanceof BigDecimal p && p.compareTo(low) >= 0 && p.compareTo(high) <= 0;
}
@Override public boolean evaluate(RowSet rs) {
try { return inRange(rs.getBigDecimal("PRICE")); }
catch (SQLException e) { return false; }
}
@Override public boolean evaluate(Object value, int column) { return column != 4 || inRange(value); }
@Override public boolean evaluate(Object value, String columnName) { return !columnName.equalsIgnoreCase("PRICE") || inRange(value); }
}
static List<String> column(ResultSet rs, String name) throws SQLException {
var out = new ArrayList<String>();
rs.beforeFirst();
while (rs.next()) out.add(rs.getString(name));
return out;
}
public static void main(String[] args) throws Exception {
System.out.println("--- CachedRowSet with a listener ---");
CachedRowSet crs = fill(FACTORY.createCachedRowSet(), "PRODUCTS", PRODUCT_COLUMNS, PRODUCT_TYPES, PRODUCTS);
RowSetListener listener = new RowSetListener() {
@Override public void rowSetChanged(RowSetEvent e) { System.out.println(" event: row set changed"); }
@Override public void rowChanged(RowSetEvent e) { System.out.println(" event: row changed"); }
@Override public void cursorMoved(RowSetEvent e) { }
};
crs.addRowSetListener(listener);
crs.absolute(2);
crs.updateBigDecimal("PRICE", new BigDecimal("79.00"));
crs.updateRow();
System.out.println("names: " + column(crs, "NAME"));
crs.removeRowSetListener(listener); // listeners would be serialized too
System.out.println("--- serializing a disconnected row set ---");
var bytes = new ByteArrayOutputStream();
try (var out = new ObjectOutputStream(bytes)) { out.writeObject(crs); }
CachedRowSet copy;
try (var in = new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray()))) { copy = (CachedRowSet) in.readObject(); }
copy.absolute(2);
System.out.println("copy row 2: " + copy.getString("NAME") + " " + copy.getBigDecimal("PRICE") + ", updated " + copy.rowUpdated());
System.out.println("--- FilteredRowSet ---");
FilteredRowSet frs = fill(FACTORY.createFilteredRowSet(), "PRODUCTS", PRODUCT_COLUMNS, PRODUCT_TYPES, PRODUCTS);
frs.setFilter(new PriceRange("15", "50"));
System.out.println("15 to 50: " + column(frs, "NAME"));
frs.moveToInsertRow();
frs.updateInt(1, 6);
frs.updateString(2, "Gold-plated drill");
frs.updateString(3, "ACME");
try {
frs.updateBigDecimal(4, new BigDecimal("999"));
frs.insertRow();
} catch (SQLException e) {
System.out.println("insert outside the filter: " + e.getMessage());
}
frs.moveToCurrentRow();
frs.setFilter(null);
System.out.println("no filter: " + column(frs, "NAME"));
System.out.println("--- JoinRowSet ---");
CachedRowSet suppliers = fill(FACTORY.createCachedRowSet(), "SUPPLIERS",
new String[] { "SUPPLIER", "COUNTRY" }, new int[] { Types.VARCHAR, Types.VARCHAR },
new Object[][] { { "ACME", "USA" }, { "NORD", "Sweden" }, { "ZETA", "Italy" } });
CachedRowSet products = fill(FACTORY.createCachedRowSet(), "PRODUCTS", PRODUCT_COLUMNS, PRODUCT_TYPES, PRODUCTS);
JoinRowSet jrs = FACTORY.createJoinRowSet();
jrs.addRowSet(products, "SUPPLIER");
jrs.addRowSet(suppliers, "SUPPLIER");
var joined = new TreeSet<String>();
jrs.beforeFirst();
while (jrs.next()) joined.add(jrs.getString("NAME") + " (" + jrs.getString("COUNTRY") + ")");
System.out.println(joined);
System.out.println("--- WebRowSet as XML ---");
WebRowSet wrs = fill(FACTORY.createWebRowSet(), "PRODUCTS", PRODUCT_COLUMNS, PRODUCT_TYPES,
Arrays.copyOf(PRODUCTS, 2));
wrs.absolute(1);
wrs.updateString("NAME", "Claw hammer");
wrs.updateRow();
var xml = new StringWriter();
wrs.writeXml(xml);
String text = xml.toString();
System.out.println("XML sections: " + text.lines().map(String::strip)
.filter(l -> l.matches("<(properties|metadata|data)>")).toList());
System.out.println("rows in XML: currentRow=" + count(text, "<currentRow>") + ", modifyRow=" + count(text, "<modifyRow>")
);
WebRowSet back = FACTORY.createWebRowSet();
back.readXml(new StringReader(text));
System.out.println("read back: " + column(back, "NAME"));
}
static long count(String s, String tag) { return s.lines().filter(l -> l.contains(tag)).count(); }
}
--- CachedRowSet with a listener ---
event: row changed
names: [Hammer, Oak shelf, Pine stool, Desk lamp, Saw]
--- serializing a disconnected row set ---
copy row 2: Oak shelf 79.00, updated true
--- FilteredRowSet ---
15 to 50: [Pine stool, Desk lamp, Saw]
insert outside the filter: This value is not allowed through the filter
no filter: [Hammer, Oak shelf, Pine stool, Desk lamp, Saw]
--- JoinRowSet ---
[Hammer (USA), Oak shelf (Sweden), Pine stool (Sweden), Saw (USA)]
--- WebRowSet as XML ---
XML sections: [<properties>, <metadata>, <data>]
rows in XML: currentRow=1, modifyRow=1
read back: [Claw hammer, Oak shelf]
The JDK's row set implementation is old and has some rough edges. For example, JoinRowSet.getJoinType() fails in current JDKs, and a few cursor methods deviate from the ResultSet rules. That's another reason why new code seldom uses row sets.
Common questions
Should I use row sets in new code?
Rarely. For disconnected data, read rows into a List of records and close the connection; that is simpler, type-safe, and easy to serialize as JSON. Row sets still help when existing code expects a ResultSet, or in tests that need a ResultSet without a database, as this course's demos show.
Why do I get SyncProviderException from acceptChanges?
Another transaction changed the rows since you read them, or the row set doesn't know the table or key columns. Inspect getSyncResolver() to see the conflicts, and after populate, call setTableName and setKeyColumns.
Does a CachedRowSet work with all databases?
The JDK's implementation uses only standard JDBC, so in principle yes. Its writer generates simple UPDATE ... WHERE statements comparing all original values, which can fail with types that don't compare well (floating point, LOBs, some date types). Test with your schema.
Is JdbcRowSet different from a plain ResultSet?
Only in that it is a JavaBean: configurable with setters, observable with listeners, and always scrollable and updatable as far as the underlying driver allows. It stays connected.
Can I convert a row set to JSON or CSV?
Not built in. Iterate with next() and use ResultSetMetaData for the column names, as the metadata article (64) shows, then write the format yourself or with a library. WebRowSet.writeXml is the only built-in export format.
API reference
| API | Purpose |
|---|---|
RowSetProvider.newFactory(), RowSetFactory.createCachedRowSet, createWebRowSet, createFilteredRowSet, createJoinRowSet, createJdbcRowSet | obtain row sets |
CachedRowSet.populate(rs), execute(conn), RowSet.execute() | fill a row set |
RowSet.setCommand, setUrl, setUsername, setPassword, setDataSourceName, parameter setters | configure the query |
setPageSize, nextPage, previousPage | load large results in pages |
setTableName, setKeyColumns, acceptChanges(), acceptChanges(conn) | write changes back |
SyncProviderException.getSyncResolver(), SyncResolver.nextConflict, getConflictValue, getStatus, setResolvedValue | handle conflicts |
setOriginalRow, rowUpdated, rowInserted, rowDeleted, setShowDeleted | track changes |
WebRowSet.writeXml, readXml | XML form |
FilteredRowSet.setFilter(Predicate) | filter rows in memory |
JoinRowSet.addRowSet(rowSet, matchColumn) | join row sets in memory |
addRowSetListener, removeRowSetListener, RowSetListener | change notifications |
Summary
- Row sets extend
ResultSet. ACachedRowSetholds its rows without a connection, so you can close the connection right after the query. - Fill it with
populate(resultSet)orsetCommandplusexecute, and use pages for large results. - Edits are recorded and written back by
acceptChanges. Set the table name and key columns afterpopulate. Concurrent changes cause aSyncProviderExceptionwith aSyncResolverdescribing the conflicts. WebRowSetconverts to and from XML,FilteredRowSetfilters in memory,JoinRowSetjoins in memory, andJdbcRowSetwraps a connected result set.- Row sets are a legacy API, still supported. Modern code usually maps rows to records or entities.
Practice Questions
What advantage does a CachedRowSet have over a scrollable ResultSet in an interactive application?
A scrollable result set needs an open connection the whole time the user browses or edits. A cached row set copies the rows, so the connection can be closed (or returned to the pool) immediately after the query. Changes are written back later in one short transaction with acceptChanges.
You populated a CachedRowSet from a join query and call acceptChanges after editing. It fails. What may be missing?
After populate, the row set doesn't know which table to update or which columns identify a row. Call setTableName and setKeyColumns. Also, only changes to columns of that one table can be written. The results of joins or aggregates generally can't be written back.
What happens if another user changed a row between your populate and your acceptChanges?
The default provider checks the original values of each changed row against the database. If they no longer match, it writes nothing and throws a SyncProviderException. Use getSyncResolver() to inspect each conflict and its current database value, set the values you want with setResolvedValue, and call acceptChanges again, or reload and let the user redo the edit.
How do you avoid loading 100,000 rows into a CachedRowSet at once?
Call setPageSize(n) before execute. The row set then loads only the first n rows, and nextPage() and previousPage() load further pages. Even better, often a query with a WHERE clause or pagination (OFFSET/FETCH) should return fewer rows in the first place.
Why can't you pass a lambda like rs -\> price \> 20 to FilteredRowSet.setFilter?
setFilter takes a javax.sql.rowset.Predicate, which has three abstract evaluate methods: one for filtering rows and two for checking values on insert and update. It isn't a functional interface, so you have to write a class that implements all three.
Previous: Scrollable and Updatable Result Sets in JDBC
Next: JDBC Metadata: DatabaseMetaData, ResultSetMetaData and ParameterMetaData
Related reading
- Scrollable and Updatable Result Sets in JDBC
- LOBs, SQL Escapes, Multiple Results and Generated Keys in JDBC
- Prepared Statements in JDBC: Parameters, Reuse and Preventing SQL Injection
- Executing SQL with JDBC: Statements, Result Sets and SQL Exceptions
- Connecting to a Database with JDBC: URLs, Drivers, DriverManager and DataSource

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.