repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter10/P214_VirtualThreadsAndSyncCode1/src/main/java/modern/challenge/Main.java
Chapter10/P214_VirtualThreadsAndSyncCode1/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.time.Duration; import java.util.concurrent.SynchronousQueue; import java.util.logging.Logger; public class Main { private static final Logger logger = Logger.getLogger(Main.class.getName()); public static void main(String[] args) throws InterruptedException { SynchronousQueue<Integer> queue = new SynchronousQueue<>(); System.setProperty("java.util.logging.SimpleFormatter.format", "[%1$tT] [%4$-7s] %5$s %n"); Runnable task = () -> { logger.info(() -> Thread.currentThread().toString() + " sleeps for 5 seconds"); try { Thread.sleep(Duration.ofSeconds(5)); } catch (InterruptedException ex) {} logger.info(() -> Thread.currentThread().toString() + " inserts in the queue"); queue.offer(Integer.MAX_VALUE); }; logger.info("Before running the task ..."); // Thread.startVirtualThread(task); Thread vThread = Thread.ofVirtual().start(task); logger.info(vThread.toString()); logger.info(() -> Thread.currentThread().toString() + " can't take from the queue yet"); int maxint = queue.take(); logger.info(() -> Thread.currentThread().toString() + "took from queue: " + maxint); logger.info(vThread.toString()); logger.info("After running the task ..."); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter10/P212_IntroNewVirtualThreadPerTaskExecutor/src/main/java/modern/challenge/Main.java
Chapter10/P212_IntroNewVirtualThreadPerTaskExecutor/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.logging.Logger; public class Main { private static final Logger logger = Logger.getLogger(Main.class.getName()); private static final int NUMBER_OF_TASKS = 15; static class SimpleThreadFactory implements ThreadFactory { @Override public Thread newThread(Runnable r) { return new Thread(r); // classic thread //return Thread.ofVirtual().unstarted(r); // virtual thread } } public static void main(String[] args) throws InterruptedException, ExecutionException { System.setProperty("java.util.logging.SimpleFormatter.format", "[%1$tT] [%4$-7s] %5$s %n"); Runnable taskr = () -> logger.info(Thread.currentThread().toString()); Callable<Boolean> taskc = () -> { logger.info(Thread.currentThread().toString()); return true; }; System.out.println("\nRunnable:"); try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) { for (int i = 0; i < NUMBER_OF_TASKS; i++) { executor.submit(taskr); // Future<?> future = executor.submit(taskr); } } System.out.println("\nCallable:"); try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) { for (int i = 0; i < NUMBER_OF_TASKS; i++) { executor.submit(taskc); // Future<Boolean> future = executor.submit(taskc); } } System.out.println("\nRunnable:"); try (ExecutorService executor = Executors.newThreadPerTaskExecutor(new SimpleThreadFactory())) { for (int i = 0; i < NUMBER_OF_TASKS; i++) { executor.submit(taskr); // Future<?> future = executor.submit(taskr); } } System.out.println("\nCallable:"); try (ExecutorService executor = Executors.newThreadPerTaskExecutor(new SimpleThreadFactory())) { for (int i = 0; i < NUMBER_OF_TASKS; i++) { executor.submit(taskc); // Future<Boolean> future = executor.submit(taskc); } } } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter10/P218_HookingTaskState/src/main/java/modern/challenge/UserNotFoundException.java
Chapter10/P218_HookingTaskState/src/main/java/modern/challenge/UserNotFoundException.java
package modern.challenge; public class UserNotFoundException extends RuntimeException { public UserNotFoundException(String message) { super(message); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter10/P218_HookingTaskState/src/main/java/modern/challenge/Main.java
Chapter10/P218_HookingTaskState/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import static java.util.concurrent.Future.State.CANCELLED; import static java.util.concurrent.Future.State.FAILED; import static java.util.concurrent.Future.State.RUNNING; import static java.util.concurrent.Future.State.SUCCESS; import java.util.concurrent.ThreadLocalRandom; import java.util.logging.Logger; public class Main { private static final Logger logger = Logger.getLogger(Main.class.getName()); public static void main(String[] args) throws InterruptedException { System.setProperty("java.util.logging.SimpleFormatter.format", "[%1$tT] [%4$-7s] %5$s %n"); buildTestingTeam(); } public static TestingTeam buildTestingTeam() throws InterruptedException { List<String> testers = new ArrayList<>(); try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) { List<Future<String>> futures = executor.invokeAll( List.of(() -> fetchTester(Integer.MAX_VALUE), () -> fetchTester(2), () -> fetchTester(Integer.MAX_VALUE)) ); futures.forEach(f -> { logger.info(() -> "Analyzing " + f + " state ..."); switch (f.state()) { case RUNNING -> throw new IllegalStateException("Future is still in the running state ..."); case SUCCESS -> { logger.info(() -> "Result: " + f.resultNow()); testers.add(f.resultNow()); } case FAILED -> logger.severe(() -> "Exception: " + f.exceptionNow().getMessage()); case CANCELLED -> logger.info("Cancelled ?!?"); } }); } return new TestingTeam(testers.toArray(String[]::new)); } public static String fetchTester(int id) throws IOException, InterruptedException { HttpClient client = HttpClient.newHttpClient(); // intentionally added a delay of 1-5 seconds Thread.sleep(Duration.ofMillis(ThreadLocalRandom.current().nextLong(5000))); HttpRequest requestGet = HttpRequest.newBuilder() .GET() .uri(URI.create("https://reqres.in/api/users/" + id)) .build(); HttpResponse<String> responseGet = client.send( requestGet, HttpResponse.BodyHandlers.ofString()); if (responseGet.statusCode() == 200) { return responseGet.body(); } throw new UserNotFoundException("Code: " + responseGet.statusCode()); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter10/P218_HookingTaskState/src/main/java/modern/challenge/TestingTeam.java
Chapter10/P218_HookingTaskState/src/main/java/modern/challenge/TestingTeam.java
package modern.challenge; public record TestingTeam(String... testers) {}
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter10/P220_IntroStructuredTaskScope/src/main/java/modern/challenge/UserNotFoundException.java
Chapter10/P220_IntroStructuredTaskScope/src/main/java/modern/challenge/UserNotFoundException.java
package modern.challenge; public class UserNotFoundException extends RuntimeException { public UserNotFoundException(String message) { super(message); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter10/P220_IntroStructuredTaskScope/src/main/java/modern/challenge/Main.java
Chapter10/P220_IntroStructuredTaskScope/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.util.logging.Logger; import java.util.concurrent.StructuredTaskScope; import java.util.concurrent.StructuredTaskScope.Subtask; public class Main { private static final Logger logger = Logger.getLogger(Main.class.getName()); public static void main(String[] args) throws InterruptedException { System.setProperty("java.util.logging.SimpleFormatter.format", "[%1$tT] [%4$-7s] %5$s %n"); buildTestingTeam(); } public static TestingTeam buildTestingTeam() throws InterruptedException { try (StructuredTaskScope scope = new StructuredTaskScope<String>()) { Subtask<String> subtask = scope.fork(() -> fetchTester(1)); // non-blocking operation logger.info(() -> "Waiting for " + subtask.toString() + " to finish ...\n"); scope.join(); // blocking operation /* String result = ""; if (subtask.state().equals(Subtask.State.SUCCESS)) { result = subtask.get(); } */ String result = subtask.get(); // non-blocking operation logger.info(result); return new TestingTeam(result); } } public static String fetchTester(int id) throws IOException, InterruptedException { HttpClient client = HttpClient.newHttpClient(); HttpRequest requestGet = HttpRequest.newBuilder() .GET() .uri(URI.create("https://reqres.in/api/users/" + id)) .build(); HttpResponse<String> responseGet = client.send( requestGet, HttpResponse.BodyHandlers.ofString()); if (responseGet.statusCode() == 200) { return responseGet.body(); } throw new UserNotFoundException("Code: " + responseGet.statusCode()); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter10/P220_IntroStructuredTaskScope/src/main/java/modern/challenge/TestingTeam.java
Chapter10/P220_IntroStructuredTaskScope/src/main/java/modern/challenge/TestingTeam.java
package modern.challenge; public record TestingTeam(String... testers) {}
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter10/P224_MonitoringVirtualThreadsJmx4/src/main/java/modern/challenge/UserNotFoundException.java
Chapter10/P224_MonitoringVirtualThreadsJmx4/src/main/java/modern/challenge/UserNotFoundException.java
package modern.challenge; public class UserNotFoundException extends RuntimeException { public UserNotFoundException(String message) { super(message); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter10/P224_MonitoringVirtualThreadsJmx4/src/main/java/modern/challenge/Main.java
Chapter10/P224_MonitoringVirtualThreadsJmx4/src/main/java/modern/challenge/Main.java
package modern.challenge; import com.sun.management.HotSpotDiagnosticMXBean; import java.io.IOException; import java.lang.management.ManagementFactory; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.nio.file.Path; import java.time.Duration; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.StructuredTaskScope; import java.util.concurrent.StructuredTaskScope.ShutdownOnSuccess; import java.util.concurrent.ThreadLocalRandom; import java.util.logging.Logger; import java.util.stream.Stream; public class Main { private static final Logger logger = Logger.getLogger(Main.class.getName()); public static void main(String[] args) throws InterruptedException, IOException, ExecutionException { System.setProperty("java.util.logging.SimpleFormatter.format", "[%1$tT] [%4$-7s] %5$s %n"); try (ShutdownOnSuccess scope = new StructuredTaskScope.ShutdownOnSuccess<String>()) { Stream.of(1, 2, 3) .<Callable<String>>map(id -> () -> fetchTester(id)) .forEach(scope::fork); HotSpotDiagnosticMXBean mBean = ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class); mBean.dumpThreads(Path.of("dumpThreads.json").toAbsolutePath().toString(), HotSpotDiagnosticMXBean.ThreadDumpFormat.JSON); scope.join(); String result = (String) scope.result(); logger.info(result); } } public static String fetchTester(int id) throws IOException, InterruptedException { HttpClient client = HttpClient.newHttpClient(); // intentionally added a delay of 1-5 seconds logger.info(() -> Thread.currentThread().toString()); Thread.sleep(Duration.ofMillis(ThreadLocalRandom.current().nextLong(5000))); HttpRequest requestGet = HttpRequest.newBuilder() .GET() .uri(URI.create("https://reqres.in/api/users/" + id)) .build(); HttpResponse<String> responseGet = client.send( requestGet, HttpResponse.BodyHandlers.ofString()); if (responseGet.statusCode() == 200) { return responseGet.body(); } throw new UserNotFoundException("Code: " + responseGet.statusCode()); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter10/P217_InvokeAnyOnSuccess/src/main/java/modern/challenge/UserNotFoundException.java
Chapter10/P217_InvokeAnyOnSuccess/src/main/java/modern/challenge/UserNotFoundException.java
package modern.challenge; public class UserNotFoundException extends RuntimeException { public UserNotFoundException(String message) { super(message); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter10/P217_InvokeAnyOnSuccess/src/main/java/modern/challenge/Main.java
Chapter10/P217_InvokeAnyOnSuccess/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Duration; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadLocalRandom; import java.util.logging.Logger; public class Main { private static final Logger logger = Logger.getLogger(Main.class.getName()); public static void main(String[] args) throws InterruptedException, ExecutionException { System.setProperty("java.util.logging.SimpleFormatter.format", "[%1$tT] [%4$-7s] %5$s %n"); buildTestingTeam(); } public static TestingTeam buildTestingTeam() throws InterruptedException, ExecutionException { try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) { String result = executor.invokeAny( List.of(() -> fetchTester(1), () -> fetchTester(2), () -> fetchTester(3)) ); logger.info(result); return new TestingTeam(result); } } public static String fetchTester(int id) throws IOException, InterruptedException { HttpClient client = HttpClient.newHttpClient(); // intentionally added a delay of 1-5 seconds Thread.sleep(Duration.ofMillis(ThreadLocalRandom.current().nextLong(5000))); HttpRequest requestGet = HttpRequest.newBuilder() .GET() .uri(URI.create("https://reqres.in/api/users/" + id)) .build(); HttpResponse<String> responseGet = client.send( requestGet, HttpResponse.BodyHandlers.ofString()); if (responseGet.statusCode() == 200) { return responseGet.body(); } throw new UserNotFoundException("Code: " + responseGet.statusCode()); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter10/P217_InvokeAnyOnSuccess/src/main/java/modern/challenge/TestingTeam.java
Chapter10/P217_InvokeAnyOnSuccess/src/main/java/modern/challenge/TestingTeam.java
package modern.challenge; public record TestingTeam(String... testers) {}
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter10/P211_IntroVirtualThreadFactory/src/main/java/modern/challenge/Main.java
Chapter10/P211_IntroVirtualThreadFactory/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.util.concurrent.ThreadFactory; import java.util.logging.Logger; public class Main { private static final Logger logger = Logger.getLogger(Main.class.getName()); static class SimpleThreadFactory implements ThreadFactory { @Override public Thread newThread(Runnable r) { // return new Thread(r); // platform thread return Thread.ofVirtual().unstarted(r); // virtual thread } } public static void main(String[] args) { System.setProperty("java.util.logging.SimpleFormatter.format", "[%1$tT] [%4$-7s] %5$s %n"); Runnable task = () -> logger.info(Thread.currentThread().toString()); // ThreadFactory tfVirtual = Thread.ofVirtual().factory(); ThreadFactory tfVirtual = Thread.ofVirtual().name("vt-", 0).factory(); // Thread.Builder builder = Thread.ofVirtual().name("vt-", 0); // ThreadFactory tfVirtual = builder.factory(); ThreadFactory tfPlatform = Thread.ofPlatform().name("pt-", 0).factory(); SimpleThreadFactory stf = new SimpleThreadFactory(); tfVirtual.newThread(task).start(); tfPlatform.newThread(task).start(); stf.newThread(task).start(); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter10/P211_IntroStartVirtualThread/src/main/java/modern/challenge/Main.java
Chapter10/P211_IntroStartVirtualThread/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.util.logging.Logger; public class Main { private static final Logger logger = Logger.getLogger(Main.class.getName()); public static void main(String[] args) throws InterruptedException { System.setProperty("java.util.logging.SimpleFormatter.format", "[%1$tT] [%4$-7s] %5$s %n"); Runnable task = () -> logger.info(Thread.currentThread().toString()); logger.info("Before running the task ..."); // Thread.ofVirtual().start(task); // Thread.ofVirtual().name("my_vThread").start(task); // Thread.Builder builder = Thread.ofVirtual().name("my_vThread"); // Thread vThread = builder.start(task); Thread vThread = Thread.startVirtualThread(task); logger.info("While running the task ..."); vThread.join(); logger.info("After running the task ..."); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter10/P211_IntroCheckVirtualThread/src/main/java/modern/challenge/Main.java
Chapter10/P211_IntroCheckVirtualThread/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.util.logging.Logger; public class Main { private static final Logger logger = Logger.getLogger(Main.class.getName()); public static void main(String[] args) { System.setProperty("java.util.logging.SimpleFormatter.format", "[%1$tT] [%4$-7s] %5$s %n"); Runnable task = () -> logger.info(Thread.currentThread().toString()); Thread vThread = Thread.ofVirtual().name("my_vThread").unstarted(task); Thread pThread1 = Thread.ofPlatform().name("my_pThread").unstarted(task); Thread pThread2 = new Thread(() -> {}); logger.info(() -> "Is vThread virtual ? " + vThread.isVirtual()); logger.info(() -> "Is pThread1 virtual ? " + pThread1.isVirtual()); logger.info(() -> "Is pThread2 virtual ? " + pThread2.isVirtual()); logger.info(() -> "Is daemon ? " + vThread.isDaemon()); // vThread.setDaemon(false); // java.lang.IllegalArgumentException: 'false' not legal for virtual threads logger.info(() -> "Priority ? " + vThread.getPriority()); // NORM_PRIORITY = 5 vThread.setPriority(4); logger.info(() -> "Priority (after setting it 4) ? " + vThread.getPriority()); // NORM_PRIORITY = 5 logger.info(() -> "Thread group ? " + vThread.getThreadGroup().getName()); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter10/P223_StructuredTaskScopeStream1/src/main/java/modern/challenge/UserNotFoundException.java
Chapter10/P223_StructuredTaskScopeStream1/src/main/java/modern/challenge/UserNotFoundException.java
package modern.challenge; public class UserNotFoundException extends RuntimeException { public UserNotFoundException(String message) { super(message); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter10/P223_StructuredTaskScopeStream1/src/main/java/modern/challenge/Main.java
Chapter10/P223_StructuredTaskScopeStream1/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Duration; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ThreadLocalRandom; import java.util.logging.Logger; import java.util.stream.Stream; import java.util.concurrent.StructuredTaskScope; import java.util.concurrent.StructuredTaskScope.ShutdownOnSuccess; public class Main { private static final Logger logger = Logger.getLogger(Main.class.getName()); public static void main(String[] args) throws InterruptedException, ExecutionException { System.setProperty("java.util.logging.SimpleFormatter.format", "[%1$tT] [%4$-7s] %5$s %n"); buildTestingTeam(); } public static TestingTeam buildTestingTeam() throws InterruptedException, ExecutionException { try (ShutdownOnSuccess scope = new StructuredTaskScope.ShutdownOnSuccess<String>()) { Stream.of(1, 2, 3) .<Callable<String>>map(id -> () -> fetchTester(id)) .forEach(scope::fork); scope.join(); String result = (String) scope.result(); logger.info(result); return new TestingTeam(result); } } public static String fetchTester(int id) throws IOException, InterruptedException { HttpClient client = HttpClient.newHttpClient(); // intentionally added a delay of 1-5 seconds Thread.sleep(Duration.ofMillis(ThreadLocalRandom.current().nextLong(5000))); HttpRequest requestGet = HttpRequest.newBuilder() .GET() .uri(URI.create("https://reqres.in/api/users/" + id)) .build(); HttpResponse<String> responseGet = client.send( requestGet, HttpResponse.BodyHandlers.ofString()); if (responseGet.statusCode() == 200) { return responseGet.body(); } throw new UserNotFoundException("Code: " + responseGet.statusCode()); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter10/P223_StructuredTaskScopeStream1/src/main/java/modern/challenge/TestingTeam.java
Chapter10/P223_StructuredTaskScopeStream1/src/main/java/modern/challenge/TestingTeam.java
package modern.challenge; public record TestingTeam(String... testers) {}
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter10/P210_UnstructuredConcurrencySample/src/main/java/modern/challenge/UserNotFoundException.java
Chapter10/P210_UnstructuredConcurrencySample/src/main/java/modern/challenge/UserNotFoundException.java
package modern.challenge; public class UserNotFoundException extends RuntimeException { public UserNotFoundException(String message) { super(message); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter10/P210_UnstructuredConcurrencySample/src/main/java/modern/challenge/Main.java
Chapter10/P210_UnstructuredConcurrencySample/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; public class Main { private static final Logger logger = Logger.getLogger(Main.class.getName()); private static final ExecutorService executor = Executors.newFixedThreadPool(2); public static void main(String[] args) throws InterruptedException, ExecutionException { System.setProperty("java.util.logging.SimpleFormatter.format", "[%1$tT] [%4$-7s] %5$s %n"); buildTestingTeam(); } public static TestingTeam buildTestingTeam() throws InterruptedException { // STOP 1 Future<String> future1 = futureTester(1); Future<String> future2 = futureTester(2); // Integer.MAX_VALUE Future<String> future3 = futureTester(3); try { // STOP 2 String tester1 = future1.get(); String tester2 = future2.get(); String tester3 = future3.get(); logger.info(tester1); logger.info(tester2); logger.info(tester3); return new TestingTeam(tester1, tester2, tester3); } catch (ExecutionException ex) { // STOP 3 throw new RuntimeException(ex); } finally { // STOP 4 shutdownExecutor(executor); } } // STOP 5 public static Future<String> futureTester(int id) { return executor.submit(() -> fetchTester(id)); } public static String fetchTester(int id) throws IOException, InterruptedException { HttpClient client = HttpClient.newHttpClient(); HttpRequest requestGet = HttpRequest.newBuilder() .GET() .uri(URI.create("https://reqres.in/api/users/" + id)) .build(); HttpResponse<String> responseGet = client.send( requestGet, HttpResponse.BodyHandlers.ofString()); if (responseGet.statusCode() == 200) { return responseGet.body(); } throw new UserNotFoundException("Code: " + responseGet.statusCode()); } private static boolean shutdownExecutor(ExecutorService executor) { executor.shutdown(); try { if (!executor.awaitTermination(1000, TimeUnit.MILLISECONDS)) { executor.shutdownNow(); return executor.awaitTermination(1000, TimeUnit.MILLISECONDS); } return true; } catch (InterruptedException ex) { executor.shutdownNow(); Thread.currentThread().interrupt(); logger.severe(() -> "Exception: " + ex); } return false; } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter10/P210_UnstructuredConcurrencySample/src/main/java/modern/challenge/TestingTeam.java
Chapter10/P210_UnstructuredConcurrencySample/src/main/java/modern/challenge/TestingTeam.java
package modern.challenge; public record TestingTeam(String... testers) {}
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter10/P223_StructuredTaskScopeStream2/src/main/java/modern/challenge/UserNotFoundException.java
Chapter10/P223_StructuredTaskScopeStream2/src/main/java/modern/challenge/UserNotFoundException.java
package modern.challenge; public class UserNotFoundException extends RuntimeException { public UserNotFoundException(String message) { super(message); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter10/P223_StructuredTaskScopeStream2/src/main/java/modern/challenge/Main.java
Chapter10/P223_StructuredTaskScopeStream2/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Duration; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ThreadLocalRandom; import java.util.logging.Logger; import static java.util.stream.Collectors.collectingAndThen; import static java.util.stream.Collectors.toList; import java.util.stream.Stream; import java.util.concurrent.StructuredTaskScope; import java.util.concurrent.StructuredTaskScope.ShutdownOnSuccess; import java.util.concurrent.StructuredTaskScope.Subtask; public class Main { private static final Logger logger = Logger.getLogger(Main.class.getName()); public static void main(String[] args) throws InterruptedException, ExecutionException { System.setProperty("java.util.logging.SimpleFormatter.format", "[%1$tT] [%4$-7s] %5$s %n"); buildTestingTeam(); } public static TestingTeam buildTestingTeam() throws InterruptedException, ExecutionException { try (ShutdownOnSuccess scope = new StructuredTaskScope.ShutdownOnSuccess<String>()) { List<Subtask> subtasks = Stream.of(Integer.MAX_VALUE, 2, 3) .<Callable<String>>map(id -> () -> fetchTester(id)) .map(scope::fork) .toList(); scope.join(); List<Throwable> failed = subtasks.stream() .filter(f -> f.state() == Subtask.State.FAILED) .map(Subtask::exception) .toList(); logger.info(failed.toString()); TestingTeam result = subtasks.stream() .filter(f -> f.state() == Subtask.State.SUCCESS) .map(Subtask::get) .collect(collectingAndThen(toList(), list -> { return new TestingTeam(list.toArray(String[]::new)); })); logger.info(result.toString()); return result; } } public static String fetchTester(int id) throws IOException, InterruptedException { HttpClient client = HttpClient.newHttpClient(); // intentionally added a delay of 1-5 seconds Thread.sleep(Duration.ofMillis(ThreadLocalRandom.current().nextLong(5000))); HttpRequest requestGet = HttpRequest.newBuilder() .GET() .uri(URI.create("https://reqres.in/api/users/" + id)) .build(); HttpResponse<String> responseGet = client.send( requestGet, HttpResponse.BodyHandlers.ofString()); if (responseGet.statusCode() == 200) { return responseGet.body(); } throw new UserNotFoundException("Code: " + responseGet.statusCode()); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter10/P223_StructuredTaskScopeStream2/src/main/java/modern/challenge/TestingTeam.java
Chapter10/P223_StructuredTaskScopeStream2/src/main/java/modern/challenge/TestingTeam.java
package modern.challenge; public record TestingTeam(String... testers) {}
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter10/P224_MonitoringVirtualThreadsJmx3/src/main/java/modern/challenge/Main.java
Chapter10/P224_MonitoringVirtualThreadsJmx3/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.lang.management.ManagementFactory; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import java.time.Duration; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; import java.util.stream.IntStream; public class Main { private static final Logger logger = Logger.getLogger(Main.class.getName()); public static void main(String[] args) throws InterruptedException { System.setProperty("java.util.logging.SimpleFormatter.format", "[%1$tT] [%4$-7s] %5$s %n"); logger.info("Sleeping 15s ... "); Thread.sleep(Duration.ofSeconds(15)); // connect 'jconsole' while sleeping logger.info("Done ... "); ScheduledExecutorService scheduledExecutor = Executors.newScheduledThreadPool(1); scheduledExecutor.scheduleAtFixedRate(() -> { ThreadMXBean threadBean = ManagementFactory.getThreadMXBean(); ThreadInfo[] threadInfo = threadBean.dumpAllThreads(false, false); logger.info(() -> "Platform threads: " + threadInfo.length); }, 500, 500, TimeUnit.MILLISECONDS); long start = System.currentTimeMillis(); try (ExecutorService executorVirtual = Executors.newVirtualThreadPerTaskExecutor()) { IntStream.range(0, 10_000).forEach(i -> { executorVirtual.submit(() -> { Thread.sleep(Duration.ofSeconds(1)); logger.info(() -> "Task: " + i); return i; }); }); } logger.info(() -> "Time (ms): " + (System.currentTimeMillis() - start)); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter10/P217_InvokeAllOnSuccess/src/main/java/modern/challenge/UserNotFoundException.java
Chapter10/P217_InvokeAllOnSuccess/src/main/java/modern/challenge/UserNotFoundException.java
package modern.challenge; public class UserNotFoundException extends RuntimeException { public UserNotFoundException(String message) { super(message); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter10/P217_InvokeAllOnSuccess/src/main/java/modern/challenge/Main.java
Chapter10/P217_InvokeAllOnSuccess/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Duration; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadLocalRandom; import java.util.logging.Logger; public class Main { private static final Logger logger = Logger.getLogger(Main.class.getName()); public static void main(String[] args) throws InterruptedException { System.setProperty("java.util.logging.SimpleFormatter.format", "[%1$tT] [%4$-7s] %5$s %n"); buildTestingTeam(); } public static TestingTeam buildTestingTeam() throws InterruptedException { try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) { List<Future<String>> futures = executor.invokeAll( List.of(() -> fetchTester(1), () -> fetchTester(2), () -> fetchTester(3)) ); futures.forEach(f -> logger.info(() -> "State: " + f.state())); return new TestingTeam(futures.get(0).resultNow(), futures.get(1).resultNow(), futures.get(2).resultNow()); } } public static String fetchTester(int id) throws IOException, InterruptedException { HttpClient client = HttpClient.newHttpClient(); // intentionally added a delay of 1-5 seconds Thread.sleep(Duration.ofMillis(ThreadLocalRandom.current().nextLong(5000))); HttpRequest requestGet = HttpRequest.newBuilder() .GET() .uri(URI.create("https://reqres.in/api/users/" + id)) .build(); HttpResponse<String> responseGet = client.send( requestGet, HttpResponse.BodyHandlers.ofString()); if (responseGet.statusCode() == 200) { return responseGet.body(); } throw new UserNotFoundException("Code: " + responseGet.statusCode()); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter10/P217_InvokeAllOnSuccess/src/main/java/modern/challenge/TestingTeam.java
Chapter10/P217_InvokeAllOnSuccess/src/main/java/modern/challenge/TestingTeam.java
package modern.challenge; public record TestingTeam(String... testers) {}
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 22/P157_WorkingWithSlicingAllocator/src/main/java/modern/challenge/Main.java
Chapter07/JDK 22/P157_WorkingWithSlicingAllocator/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.lang.foreign.Arena; import java.lang.foreign.MemorySegment; import java.lang.foreign.SegmentAllocator; import java.lang.foreign.ValueLayout; import java.util.Arrays; public class Main { public static void main(String[] args) { int[] arr1 = new int[]{1, 2, 3, 4, 5, 6}; int[] arr2 = new int[]{7, 8, 9}; int[] arr3 = new int[]{10, 11, 12, 13, 14}; try (Arena arena = Arena.ofConfined()) { MemorySegment segment1 = arena.allocateFrom(ValueLayout.JAVA_INT, arr1); MemorySegment segment2 = arena.allocateFrom(ValueLayout.JAVA_INT, arr2); MemorySegment segment3 = arena.allocateFrom(ValueLayout.JAVA_INT, arr3); System.out.println("Segment 1: " + Arrays.toString(segment1.toArray(ValueLayout.JAVA_INT))); System.out.println("Segment 2: " + Arrays.toString(segment2.toArray(ValueLayout.JAVA_INT))); System.out.println("Segment 3: " + Arrays.toString(segment3.toArray(ValueLayout.JAVA_INT))); } System.out.println(); // using a pre-allocated segment that doesn't fit all data try (Arena arena = Arena.ofConfined()) { // it should be 10 * 4 + 4 * 4 SegmentAllocator allocator = SegmentAllocator.slicingAllocator(arena.allocate(10 * 4)); MemorySegment segment1 = allocator.allocateFrom(ValueLayout.JAVA_INT, arr1); MemorySegment segment2 = allocator.allocateFrom(ValueLayout.JAVA_INT, arr2); MemorySegment segment3 = allocator.allocateFrom(ValueLayout.JAVA_INT, arr3); System.out.println("Segment 1: " + Arrays.toString(segment1.toArray(ValueLayout.JAVA_INT))); System.out.println("Segment 2: " + Arrays.toString(segment2.toArray(ValueLayout.JAVA_INT))); System.out.println("Segment 3: " + Arrays.toString(segment3.toArray(ValueLayout.JAVA_INT))); } catch (IndexOutOfBoundsException e) { System.out.println("There is not enough memory to fit all data"); // handle exception } } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 22/P167_CallingModf/src/main/java/modern/challenge/Main.java
Chapter07/JDK 22/P167_CallingModf/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.lang.foreign.Arena; import java.lang.foreign.FunctionDescriptor; import java.lang.foreign.Linker; import java.lang.foreign.MemorySegment; import java.lang.foreign.SymbolLookup; import java.lang.foreign.ValueLayout; import java.lang.invoke.MethodHandle; public class Main { public static void main(String[] args) throws Throwable { double x = 89.76655; Linker linker = Linker.nativeLinker(); SymbolLookup libLookup = linker.defaultLookup(); try (Arena arena = Arena.ofConfined()) { MemorySegment segmentModf = libLookup.find("modf").get(); MethodHandle func = linker.downcallHandle(segmentModf, FunctionDescriptor.of( ValueLayout.JAVA_DOUBLE, ValueLayout.JAVA_DOUBLE, ValueLayout.ADDRESS)); MemorySegment segmentIntptr = arena.allocate(ValueLayout.JAVA_DOUBLE); double fractional = (double) func.invokeExact(x, segmentIntptr); System.out.println("Fractional part: " + fractional + " Integer part: " + segmentIntptr.get(ValueLayout.JAVA_DOUBLE, 0)); } } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 22/P155_IntroPaddingLayout/src/main/java/modern/challenge/Main.java
Chapter07/JDK 22/P155_IntroPaddingLayout/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.lang.foreign.Arena; import java.lang.foreign.MemoryLayout; import java.lang.foreign.MemoryLayout.PathElement; import java.lang.foreign.MemorySegment; import java.lang.foreign.SequenceLayout; import java.lang.foreign.StructLayout; import java.lang.foreign.ValueLayout; import java.lang.invoke.VarHandle; public class Main { public static void main(String[] args) { System.out.println("No padding struct"); System.out.println("--------------------------------------------------"); StructLayout npStruct = MemoryLayout.structLayout( ValueLayout.JAVA_INT.withName("x"), ValueLayout.JAVA_INT.withName("y") ); VarHandle xnHandle = npStruct.varHandle(PathElement.groupElement("x")); VarHandle ynHandle = npStruct.varHandle(PathElement.groupElement("y")); try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocate(npStruct); System.out.println("\nNo padding struct size in bytes: " + segment.byteSize()); xnHandle.set(segment, 0L, 23); // offset 0 ynHandle.set(segment, 0L, 54); // offset 4 System.out.println(); System.out.println("Offset 0: " + segment.get(ValueLayout.JAVA_INT, 0)); System.out.println("Offset 4: " + segment.get(ValueLayout.JAVA_INT, 4)); } System.out.println("--------------------------------------------------"); System.out.println("\nStruct with two padding of 4 bytes"); System.out.println("--------------------------------------------------"); StructLayout wpStruct = MemoryLayout.structLayout( MemoryLayout.paddingLayout(4), // 4 bytes ValueLayout.JAVA_INT.withName("x"), MemoryLayout.paddingLayout(4), // 4 bytes ValueLayout.JAVA_INT.withName("y") ); VarHandle xpHandle = wpStruct.varHandle(PathElement.groupElement("x")); VarHandle ypHandle = wpStruct.varHandle(PathElement.groupElement("y")); try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocate(wpStruct); System.out.println("\nStruct with padding size in bytes: " + segment.byteSize()); xpHandle.set(segment, 0L, 23); // offset 4 ypHandle.set(segment, 0L, 54); // offset 12 System.out.println(); System.out.println("Offset 0: " + segment.get(ValueLayout.JAVA_INT, 0)); System.out.println("Offset 4: " + segment.get(ValueLayout.JAVA_INT, 4)); System.out.println("Offset 8: " + segment.get(ValueLayout.JAVA_INT, 8)); System.out.println("Offset 12: " + segment.get(ValueLayout.JAVA_INT, 12)); } System.out.println("--------------------------------------------------"); MemorySegment segmenta = Arena.ofAuto().allocate(12); segmenta.set(ValueLayout.JAVA_INT, 0, 1000); segmenta.set(ValueLayout.JAVA_CHAR, 4, 'a'); segmenta.set(ValueLayout.JAVA_INT, 8, 2000); // try it out with 6 instead of 8 System.out.println("\nStruct with padding for fixing alignment"); System.out.println("----------------------Case 1----------------------"); StructLayout product1 = MemoryLayout.structLayout( ValueLayout.JAVA_INT.withName("sku"), ValueLayout.JAVA_CHAR.withName("energy"), ValueLayout.JAVA_BYTE.withName("weight")); System.out.println("Size: " + product1.byteSize()); System.out.println("Alignment: " + product1.byteAlignment()); System.out.println("Sku byte offset: " + product1.byteOffset(PathElement.groupElement("sku"))); System.out.println("Energy byte offset: " + product1.byteOffset(PathElement.groupElement("energy"))); System.out.println("Weight byte offset: " + product1.byteOffset(PathElement.groupElement("weight"))); VarHandle spHandle1 = product1.varHandle(PathElement.groupElement("sku")); VarHandle epHandle1 = product1.varHandle(PathElement.groupElement("energy")); VarHandle wpHandle1 = product1.varHandle(PathElement.groupElement("weight")); try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocate(product1); spHandle1.set(segment, 0L, 10102); epHandle1.set(segment, 0L, 'D'); wpHandle1.set(segment, 0L, (byte) 12); System.out.println(); System.out.println("Sku: " + spHandle1.get(segment, 0L)); System.out.println("Energy: " + epHandle1.get(segment, 0L)); System.out.println("Weight: " + wpHandle1.get(segment, 0L)); } System.out.println("--------------------------------------------------"); System.out.println(); System.out.println("----------------------Case 2----------------------"); StructLayout product2 = MemoryLayout.structLayout( ValueLayout.JAVA_CHAR.withName("energy"), MemoryLayout.paddingLayout(2), ValueLayout.JAVA_INT.withName("sku"), ValueLayout.JAVA_BYTE.withName("weight") ); System.out.println("Size: " + product2.byteSize()); System.out.println("Alignment: " + product2.byteAlignment()); System.out.println("Energy byte offset: " + product2.byteOffset(PathElement.groupElement("energy"))); System.out.println("Sku byte offset: " + product2.byteOffset(PathElement.groupElement("sku"))); System.out.println("Weight byte offset: " + product2.byteOffset(PathElement.groupElement("weight"))); // use arrayElementVarHandle() VarHandle erHandle2 = ValueLayout.JAVA_CHAR.arrayElementVarHandle(); VarHandle srHandle2 = ValueLayout.JAVA_INT.arrayElementVarHandle(); VarHandle wrHandle2 = ValueLayout.JAVA_BYTE.arrayElementVarHandle(); try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocate(product2); erHandle2.set(segment, 0L, 0, 'D'); srHandle2.set(segment, 0L, 1, 10102); wrHandle2.set(segment, 0L, 2, (byte) 12); System.out.println(); System.out.println("Energy: " + erHandle2.get(segment, 0L, 0)); System.out.println("Sku: " + srHandle2.get(segment, 0L, 1)); System.out.println("Weight: " + wrHandle2.get(segment, 0L, 2)); } // use PathElement VarHandle epHandle2 = product2.varHandle(PathElement.groupElement("energy")); VarHandle spHandle2 = product2.varHandle(PathElement.groupElement("sku")); VarHandle wpHandle2 = product2.varHandle(PathElement.groupElement("weight")); try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocate(product2); epHandle2.set(segment, 0L, 'D'); spHandle2.set(segment, 0L, 10102); wpHandle2.set(segment, 0L, (byte) 12); System.out.println(); System.out.println("Energy: " + epHandle2.get(segment, 0L)); System.out.println("Sku: " + spHandle2.get(segment, 0L)); System.out.println("Weight: " + wpHandle2.get(segment, 0L)); } System.out.println("--------------------------------------------------"); System.out.println(); System.out.println("----------------------Case 3----------------------"); SequenceLayout product3 = MemoryLayout.sequenceLayout( 2, MemoryLayout.structLayout( ValueLayout.JAVA_CHAR.withName("energy"), MemoryLayout.paddingLayout(2), ValueLayout.JAVA_INT.withName("sku"), ValueLayout.JAVA_BYTE.withName("weight"), MemoryLayout.paddingLayout(3) )); System.out.println("Size: " + product3.byteSize()); System.out.println("Alignment: " + product3.byteAlignment()); System.out.println("Energy byte offset (0): " + product3.byteOffset( PathElement.sequenceElement(0), PathElement.groupElement("energy"))); System.out.println("Energy byte offset (1): " + product3.byteOffset( PathElement.sequenceElement(1), PathElement.groupElement("energy"))); System.out.println("Sku byte offset (0): " + product3.byteOffset( PathElement.sequenceElement(0), PathElement.groupElement("sku"))); System.out.println("Sku byte offset (1): " + product3.byteOffset( PathElement.sequenceElement(1), PathElement.groupElement("sku"))); System.out.println("Weight byte offset (0): " + product3.byteOffset( PathElement.sequenceElement(0), PathElement.groupElement("weight"))); System.out.println("Weight byte offset (1): " + product3.byteOffset( PathElement.sequenceElement(1), PathElement.groupElement("weight"))); // use PathElement VarHandle epHandle3 = product3.varHandle( PathElement.sequenceElement(), PathElement.groupElement("energy")); VarHandle spHandle3 = product3.varHandle( PathElement.sequenceElement(), PathElement.groupElement("sku")); VarHandle wpHandle3 = product3.varHandle( PathElement.sequenceElement(), PathElement.groupElement("weight")); try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocate(product3); epHandle3.set(segment, 0L, 0, 'D'); spHandle3.set(segment, 0L, 0, 10102); wpHandle3.set(segment, 0L, 0, (byte) 12); epHandle3.set(segment, 0L, 1, 'A'); spHandle3.set(segment, 0L, 1, 454402); wpHandle3.set(segment, 0L, 1, (byte) 9); System.out.println(); System.out.println("Energy (1): " + epHandle3.get(segment, 0L, 0)); System.out.println("Sku (1): " + spHandle3.get(segment, 0L, 0)); System.out.println("Weight (1): " + wpHandle3.get(segment, 0L, 0)); System.out.println(); System.out.println("Energy (2): " + epHandle3.get(segment, 0L, 1)); System.out.println("Sku (2): " + spHandle3.get(segment, 0L, 1)); System.out.println("Weight (2): " + wpHandle3.get(segment, 0L, 1)); } System.out.println("--------------------------------------------------"); System.out.println(); System.out.println("----------------------Case 4----------------------"); StructLayout product4 = MemoryLayout.structLayout( ValueLayout.JAVA_BYTE.withName("weight"), MemoryLayout.paddingLayout(1), ValueLayout.JAVA_CHAR.withName("energy"), ValueLayout.JAVA_INT.withName("sku") ); System.out.println("Size: " + product4.byteSize()); System.out.println("Alignment: " + product4.byteAlignment()); System.out.println("Weight byte offset: " + product4.byteOffset(PathElement.groupElement("weight"))); System.out.println("Energy byte offset: " + product4.byteOffset(PathElement.groupElement("energy"))); System.out.println("Sku byte offset: " + product4.byteOffset(PathElement.groupElement("sku"))); /* challenge yourself to use arrayElementVarHandle() or PathElement */ System.out.println("--------------------------------------------------"); System.out.println(); System.out.println("----------------------Case 5----------------------"); StructLayout product5 = MemoryLayout.structLayout( ValueLayout.JAVA_INT.withName("sku"), ValueLayout.JAVA_BYTE.withName("weight"), MemoryLayout.paddingLayout(1), ValueLayout.JAVA_CHAR.withName("energy") ); System.out.println("Size: " + product5.byteSize()); System.out.println("Alignment: " + product5.byteAlignment()); System.out.println("Sku byte offset: " + product5.byteOffset(PathElement.groupElement("sku"))); System.out.println("Weight byte offset: " + product5.byteOffset(PathElement.groupElement("weight"))); System.out.println("Energy byte offset: " + product5.byteOffset(PathElement.groupElement("energy"))); /* challenge yourself to use arrayElementVarHandle() or PathElement */ System.out.println("--------------------------------------------------"); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 22/P163_StreamingMemorySegment/src/main/java/modern/challenge/Main.java
Chapter07/JDK 22/P163_StreamingMemorySegment/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.lang.foreign.Arena; import java.lang.foreign.MemoryLayout; import java.lang.foreign.MemoryLayout.PathElement; import java.lang.foreign.MemorySegment; import java.lang.foreign.SequenceLayout; import java.lang.foreign.ValueLayout; import java.lang.invoke.MethodHandle; import java.lang.invoke.VarHandle; import java.util.Arrays; public class Main { public static void main(String[] args) throws Throwable { SequenceLayout xy = MemoryLayout.sequenceLayout(2, MemoryLayout.structLayout( ValueLayout.JAVA_INT.withName("x"), ValueLayout.JAVA_INT.withName("y") )); VarHandle xHandle = xy.varHandle( PathElement.sequenceElement(), PathElement.groupElement("x")); VarHandle yHandle = xy.varHandle( PathElement.sequenceElement(), PathElement.groupElement("y")); try (Arena arena = Arena.ofShared()) { MemorySegment segment = arena.allocate(xy); xHandle.set(segment, 0L, 0, 5); yHandle.set(segment, 0L, 0, 9); xHandle.set(segment, 0L, 1, 6); yHandle.set(segment, 0L, 1, 8); // sum everything int sum1 = segment.elements(xy) .map(t -> t.toArray(ValueLayout.JAVA_INT)) .flatMapToInt(t -> Arrays.stream(t)) .sum(); int sum2 = segment.elements(ValueLayout.JAVA_INT).parallel() .mapToInt(s -> s.get(ValueLayout.JAVA_INT, 0)) .sum(); System.out.println("Sum everything: " + sum1 + " " + sum2); // sum only the frist pair of x, y MethodHandle xyHandle = xy.sliceHandle(PathElement.sequenceElement()); MemorySegment subsegment = (MemorySegment) xyHandle.invoke(segment, 0L, 0); int sum3 = subsegment.elements(ValueLayout.JAVA_INT).parallel() .mapToInt(s -> s.get(ValueLayout.JAVA_INT, 0)) .sum(); System.out.println("Sum the first pair of (x, y): " + sum3); // sum y from the first pair with the second pair (x, y) var sum4 = segment.elements(xy).parallel() .map(t -> t.asSlice(4).toArray(ValueLayout.JAVA_INT)) // by offset 4 we skip the first x .flatMapToInt(t -> Arrays.stream(t)) .sum(); System.out.println("Sum y from the first pair with the second pair (x, y): " + sum4); } } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 22/P164_ArenaMappedMemorySegment/src/main/java/modern/challenge/MappedArena.java
Chapter07/JDK 22/P164_ArenaMappedMemorySegment/src/main/java/modern/challenge/MappedArena.java
package modern.challenge; import java.io.IOException; import java.lang.foreign.Arena; import java.lang.foreign.MemorySegment; import java.nio.channels.FileChannel; import static java.nio.channels.FileChannel.MapMode.READ_WRITE; import java.nio.file.Path; import static java.nio.file.StandardOpenOption.CREATE_NEW; import static java.nio.file.StandardOpenOption.READ; import static java.nio.file.StandardOpenOption.SPARSE; import static java.nio.file.StandardOpenOption.WRITE; public class MappedArena implements Arena { private final String fileName; private final Arena shared; public MappedArena(String fileName) { if (fileName == null) { throw new IllegalArgumentException("The file name cannot be null"); } this.fileName = fileName; this.shared = Arena.ofShared(); } @Override public MemorySegment allocate(long byteSize, long byteAlignment) { try (FileChannel file = FileChannel.open( Path.of(fileName + System.currentTimeMillis() + ".txt"), CREATE_NEW, SPARSE, READ, WRITE)) { return file.map(READ_WRITE, 0, byteSize, shared); } catch (IOException e) { throw new RuntimeException(e); } } @Override public MemorySegment.Scope scope() { return shared.scope(); } @Override public void close() { shared.close(); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 22/P164_ArenaMappedMemorySegment/src/main/java/modern/challenge/Main.java
Chapter07/JDK 22/P164_ArenaMappedMemorySegment/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.io.IOException; import java.lang.foreign.Arena; import java.lang.foreign.MemorySegment; public class Main { public static void main(String[] args) throws IOException { try (Arena arena = new MappedArena("readme")) { MemorySegment segment1 = arena.allocate(100); MemorySegment segment2 = arena.allocate(50); segment1.setString(0, "Hello"); segment2.setString(0, "World"); System.out.println(segment1.getString(0) + " " + segment2.getString(0)); } System.out.println("\n\nYou should find the files on disk in the project's root"); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 22/P159_IntroLayoutFlatenning/src/main/java/modern/challenge/Main.java
Chapter07/JDK 22/P159_IntroLayoutFlatenning/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.lang.foreign.Arena; import java.lang.foreign.MemoryLayout; import java.lang.foreign.MemoryLayout.PathElement; import java.lang.foreign.MemorySegment; import java.lang.foreign.SequenceLayout; import java.lang.foreign.ValueLayout; import java.lang.invoke.VarHandle; public class Main { public static void main(String[] args) { SequenceLayout innerSeq = MemoryLayout.sequenceLayout(5, ValueLayout.JAVA_DOUBLE); SequenceLayout outerSeq = MemoryLayout.sequenceLayout(10, innerSeq); VarHandle handle = outerSeq.varHandle( PathElement.sequenceElement(), PathElement.sequenceElement()); try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocate(outerSeq); System.out.println("Outer: " + outerSeq.elementCount()); System.out.println("Inner: " + innerSeq.elementCount()); for (int i = 0; i < outerSeq.elementCount(); i++) { for (int j = 0; j < innerSeq.elementCount(); j++) { handle.set(segment, 0L, i, j, Math.random()); } } for (int i = 0; i < outerSeq.elementCount(); i++) { System.out.print("\n-----" + i + "-----"); for (int j = 0; j < innerSeq.elementCount(); j++) { System.out.printf("\nx = %.2f", handle.get(segment, 0L, i, j)); } } // flatten and dispay System.out.println("\n\nFlatten and dispay:"); SequenceLayout flatten = outerSeq.flatten(); VarHandle fhandle = flatten.varHandle(PathElement.sequenceElement()); for (int i = 0; i < flatten.elementCount(); i++) { System.out.printf("\nx = %.2f", fhandle.get(segment, 0L, i)); } } // flatten and reallocate System.out.println("\n\nFlatten and reallocate:"); SequenceLayout flatten = outerSeq.flatten(); VarHandle fhandle = flatten.varHandle(PathElement.sequenceElement()); try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocate(flatten); System.out.println("Element count: " + flatten.elementCount()); for (int i = 0; i < flatten.elementCount(); i++) { fhandle.set(segment, 0L, i, Math.random()); } for (int i = 0; i < flatten.elementCount(); i++) { System.out.printf("\nx = %.2f", fhandle.get(segment, 0L, i)); } } } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 22/P166_CallingSumTwoInt/src/main/java/modern/challenge/Main.java
Chapter07/JDK 22/P166_CallingSumTwoInt/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.lang.foreign.Arena; import java.lang.foreign.FunctionDescriptor; import java.lang.foreign.Linker; import java.lang.foreign.MemorySegment; import java.lang.foreign.SymbolLookup; import java.lang.foreign.ValueLayout; import java.lang.invoke.MethodHandle; import java.nio.file.Path; import java.nio.file.Paths; public class Main { public static void main(String[] args) throws Throwable { Linker linker = Linker.nativeLinker(); Path path = Paths.get("lib/cpp/math.dll"); try (Arena arena = Arena.ofConfined()) { SymbolLookup libLookup = SymbolLookup.libraryLookup(path, arena); MemorySegment segmentSumTwoInt = libLookup.find("_Z9sumTwoIntii").get(); MethodHandle func = linker.downcallHandle(segmentSumTwoInt, FunctionDescriptor.of(ValueLayout.JAVA_LONG, ValueLayout.JAVA_INT, ValueLayout.JAVA_INT)); long result = (long) func.invokeExact(3, 9); System.out.println(result); } } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 22/P158_IntroSliceHandle/src/main/java/modern/challenge/Main.java
Chapter07/JDK 22/P158_IntroSliceHandle/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.lang.foreign.Arena; import java.lang.foreign.MemoryLayout; import java.lang.foreign.MemoryLayout.PathElement; import java.lang.foreign.MemorySegment; import java.lang.foreign.SequenceLayout; import java.lang.foreign.ValueLayout; import java.lang.invoke.MethodHandle; import java.lang.invoke.VarHandle; import java.util.Arrays; public class Main { public static void main(String[] args) throws Throwable { SequenceLayout innerSeq = MemoryLayout.sequenceLayout(5, ValueLayout.JAVA_DOUBLE); SequenceLayout outerSeq = MemoryLayout.sequenceLayout(10, innerSeq); VarHandle handle = outerSeq.varHandle( PathElement.sequenceElement(), PathElement.sequenceElement()); try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocate(outerSeq); System.out.println("Outer: " + outerSeq.elementCount()); System.out.println("Inner: " + innerSeq.elementCount()); for (int i = 0; i < outerSeq.elementCount(); i++) { for (int j = 0; j < innerSeq.elementCount(); j++) { handle.set(segment, 0L, i, j, Math.random()); } } for (int i = 0; i < outerSeq.elementCount(); i++) { System.out.print("\n-----" + i + "-----"); for (int j = 0; j < innerSeq.elementCount(); j++) { System.out.printf("\nx = %.5f", handle.get(segment, 0L, i, j)); } } MethodHandle mHandle = outerSeq.sliceHandle( PathElement.sequenceElement() ); System.out.println(); System.out.println("\n The third sequence of 10:" + Arrays.toString( ((MemorySegment) mHandle.invoke(segment, 0L, 3)) .toArray(ValueLayout.JAVA_DOUBLE))); } } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 22/P168_CallingStrcat/src/main/java/modern/challenge/Main.java
Chapter07/JDK 22/P168_CallingStrcat/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.lang.foreign.Arena; import java.lang.foreign.FunctionDescriptor; import java.lang.foreign.Linker; import java.lang.foreign.MemorySegment; import java.lang.foreign.SymbolLookup; import java.lang.foreign.ValueLayout; import java.lang.invoke.MethodHandle; public class Main { public static void main(String[] args) throws Throwable { String strDestination = "Hello "; String strSource = "World"; Linker linker = Linker.nativeLinker(); SymbolLookup libLookup = linker.defaultLookup(); try (Arena arena = Arena.ofConfined()) { MemorySegment segmentStrcat = libLookup.find("strcat").get(); MethodHandle func = linker.downcallHandle(segmentStrcat, FunctionDescriptor.ofVoid( ValueLayout.ADDRESS, ValueLayout.ADDRESS)); MemorySegment segmentStrSource = arena.allocate(strSource.length() + 1); segmentStrSource.setString(0, strSource); MemorySegment segmentStrDestination = arena.allocate( strSource.length() + 1 + strDestination.length() + 1); segmentStrDestination.setString(0, strDestination); func.invokeExact(segmentStrDestination, segmentStrSource); System.out.println(segmentStrDestination.getString(0)); } } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 22/P164_MappedMemorySegment/src/main/java/modern/challenge/Main.java
Chapter07/JDK 22/P164_MappedMemorySegment/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.io.IOException; import java.lang.foreign.Arena; import java.lang.foreign.MemorySegment; import java.nio.channels.FileChannel; import static java.nio.channels.FileChannel.MapMode.READ_WRITE; import java.nio.file.Path; import static java.nio.file.StandardOpenOption.CREATE; import static java.nio.file.StandardOpenOption.CREATE_NEW; import static java.nio.file.StandardOpenOption.READ; import static java.nio.file.StandardOpenOption.SPARSE; import static java.nio.file.StandardOpenOption.WRITE; public class Main { public static void main(String[] args) throws IOException { try (FileChannel file = FileChannel.open( Path.of("readme.txt"), CREATE, READ, WRITE); Arena arena = Arena.ofConfined()) { MemorySegment segment = file.map(READ_WRITE, 0, 1048576, arena); // 1 Megabyte = 1048576 bytes // 1 Gigabyte = 1073741824 bytes // write the data segment.setString(0, "This is a readme file ..."); segment.setString(1048576/2, "Here is the middle of the file ..."); segment.setString(1048576-32, "Here is the end of the file ..."); // read some data System.out.println(segment.getString(1048576/2)); } try (FileChannel file = FileChannel.open( Path.of("sparse_readme.txt"), CREATE_NEW, SPARSE, READ, WRITE); Arena arena = Arena.ofConfined()) { MemorySegment segment = file.map(READ_WRITE, 0, 1048576, arena); // 1 Megabyte = 1048576 bytes // 1 Gigabyte = 1073741824 bytes // write the data segment.setString(0, "This is a readme file ..."); segment.setString(1048576/2, "Here is the middle of the file ..."); segment.setString(1048576-32, "Here is the end of the file ..."); // read some data System.out.println(segment.getString(0)); } System.out.println("\n\nYou should find the files on disk in the project's root"); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 22/P149_ArenaMemorySegment/src/main/java/modern/challenge/Main.java
Chapter07/JDK 22/P149_ArenaMemorySegment/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.lang.foreign.Arena; import java.lang.foreign.MemorySegment; import java.lang.foreign.ValueLayout; import java.nio.charset.Charset; public class Main { public static void main(String[] args) { // globalSegment1 and globalSegment2 are never deallocated MemorySegment globalSegment1 = Arena.global().allocate(8); MemorySegment globalSegment2 = Arena.global().allocate( ValueLayout.JAVA_DOUBLE.byteSize(), ValueLayout.JAVA_DOUBLE.byteAlignment()); // autoSegment1 and autoSegment2 are automatically managed by the garbage collector MemorySegment autoSegment1 = Arena.ofAuto().allocate(8); MemorySegment autoSegment2 = Arena.ofAuto().allocate( ValueLayout.JAVA_DOUBLE.byteSize(), ValueLayout.JAVA_DOUBLE.byteAlignment()); // arenaSegment1 and arenaSegment2 are available only in the try-with-resource block try (Arena arena = Arena.ofConfined()) { MemorySegment arenaSegment1 = arena.allocate(8); MemorySegment arenaSegment2 = arena.allocate( ValueLayout.JAVA_DOUBLE.byteSize(), ValueLayout.JAVA_DOUBLE.byteAlignment()); } try (Arena arena = Arena.ofConfined()) { System.out.println("Arena is alive? " + arena.scope().isAlive()); // already has arena's scope MemorySegment segment1i1 = arena.allocate(4); MemorySegment segment1i2 = arena.allocate(ValueLayout.JAVA_INT.byteSize()); MemorySegment segment1i3 = arena.allocateFrom(ValueLayout.JAVA_INT, Integer.MAX_VALUE); // JDK 22 MemorySegment segment1d = arena.allocate(ValueLayout.JAVA_DOUBLE.byteSize(), ValueLayout.JAVA_DOUBLE.byteAlignment()); MemorySegment segment1a1 = arena.allocate(ValueLayout.JAVA_CHAR); MemorySegment segment1a2 = arena.allocateFrom(ValueLayout.JAVA_CHAR, 'a'); // JDK 22 MemorySegment segment1s = arena.allocateFrom("abcd"); // JDK 22 // equivqlent with // MemorySegment segment1s = arena.allocateFrom("abcd", Charset.defaultCharset()); // JDK 22 segment1i1.set(ValueLayout.JAVA_INT, 0, Integer.MAX_VALUE); segment1i2.set(ValueLayout.JAVA_INT, 0, Integer.MAX_VALUE); segment1d.set(ValueLayout.JAVA_DOUBLE, 0, Double.MIN_VALUE); segment1a1.setAtIndex(ValueLayout.JAVA_CHAR, 0, 'a'); MemorySegment segment2i1 = arena.allocate(4); MemorySegment segment2i2 = arena.allocate(ValueLayout.JAVA_INT); MemorySegment segment2d = arena.allocate( ValueLayout.JAVA_DOUBLE.byteSize(), ValueLayout.JAVA_DOUBLE.byteAlignment()); MemorySegment segment2a1 = arena.allocate(2); MemorySegment segment2a2 = arena.allocate( ValueLayout.JAVA_CHAR.byteSize()); MemorySegment segment2s = arena.allocate(5); // "abcd".length() + 1 = 5 segment2i1.set(ValueLayout.JAVA_INT, 0, Integer.MAX_VALUE); segment2i2.setAtIndex(ValueLayout.JAVA_INT, 0, Integer.MAX_VALUE); segment2d.set(ValueLayout.JAVA_DOUBLE, 0, Double.MAX_VALUE); segment2a1.set(ValueLayout.JAVA_CHAR, 0, 'a'); segment2a2.set(ValueLayout.JAVA_CHAR, 0, 'a'); segment2s.setString(0, "abcd"); // JDK 22 System.out.println("Segment 1i1: " + segment1i1); System.out.println("Segment 1i1 content: " + segment1i1.get(ValueLayout.JAVA_INT, 0)); System.out.println("Segment 1i2: " + segment1i2); System.out.println("Segment 1i2 content: " + segment1i2.get(ValueLayout.JAVA_INT, 0)); System.out.println("Segment 1i3: " + segment1i3); System.out.println("Segment 1i3 content: " + segment1i3.get(ValueLayout.JAVA_INT, 0)); System.out.println("Segment 2i1: " + segment2i1); System.out.println("Segment 2i1 content: " + segment2i1.get(ValueLayout.JAVA_INT, 0)); System.out.println("Segment 2i2: " + segment2i2); System.out.println("Segment 2i2 content: " + segment2i2.get(ValueLayout.JAVA_INT, 0)); System.out.println("Segment 1s: " + segment1s); System.out.println("Segment 1s content: " + segment1s.getString(0)); // JDK 22 System.out.println("Segment 2s: " + segment2s); System.out.println("Segment 2s content: " + segment2s.getString(0)); // JDK 22 System.out.println("Segment 1d: " + segment1d); System.out.println("Segment 1d content: " + segment1d.get(ValueLayout.JAVA_DOUBLE, 0)); System.out.println("Segment 2d: " + segment2d); System.out.println("Segment 2d content: " + segment2d.get(ValueLayout.JAVA_DOUBLE, 0)); System.out.println("Segment 1a1: " + segment1a1); System.out.println("Segment 1a1 content: " + segment1a1.get(ValueLayout.JAVA_CHAR, 0)); System.out.println("Segment 1a2: " + segment1a2); System.out.println("Segment 1a2 content: " + segment1a2.get(ValueLayout.JAVA_CHAR, 0)); System.out.println("Segment 2a1: " + segment2a1); System.out.println("Segment 2a1 content: " + segment2a1.getAtIndex(ValueLayout.JAVA_CHAR, 0)); System.out.println("Segment 2a2: " + segment2a2); System.out.println("Segment 2a2 content: " + segment2a2.getAtIndex(ValueLayout.JAVA_CHAR, 0)); } } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 22/P146_EngagingJNR/src/main/java/modern/challenge/SimpleMath.java
Chapter07/JDK 22/P146_EngagingJNR/src/main/java/modern/challenge/SimpleMath.java
package modern.challenge; import jnr.ffi.annotations.IgnoreError; public interface SimpleMath { @IgnoreError long sumTwoInt(int x, int y); }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 22/P146_EngagingJNR/src/main/java/modern/challenge/Main.java
Chapter07/JDK 22/P146_EngagingJNR/src/main/java/modern/challenge/Main.java
package modern.challenge; import jnr.ffi.LibraryLoader; import jnr.ffi.Platform; import jnr.ffi.provider.FFIProvider; public class Main { public static void main(String[] args) { LibraryLoader<SimpleMath> loader = FFIProvider.getSystemProvider() .createLibraryLoader(SimpleMath.class) .search("./jnr/cpp") .map("sumTwoInt", "_Z9sumTwoIntii"); if (Platform.getNativePlatform().getOS() == Platform.OS.WINDOWS) { SimpleMath simpleMath = loader.load("math"); long result = simpleMath.sumTwoInt(3, 9); System.out.println("Result: " + result); } } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 22/P150_MemorySegmentAndArray/src/main/java/module-info.java
Chapter07/JDK 22/P150_MemorySegmentAndArray/src/main/java/module-info.java
module P150_VectorTerminology { requires jdk.incubator.vector; }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 22/P150_MemorySegmentAndArray/src/main/java/modern/challenge/Main.java
Chapter07/JDK 22/P150_MemorySegmentAndArray/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.lang.foreign.Arena; import java.lang.foreign.MemorySegment; import java.lang.foreign.ValueLayout; import java.nio.ByteOrder; import java.util.Arrays; import jdk.incubator.vector.IntVector; import jdk.incubator.vector.VectorSpecies; public class Main { public static void main(String[] args) { VectorSpecies<Integer> VS256 = IntVector.SPECIES_256; IntVector v0; try (Arena arena = Arena.ofConfined()) { // 32 = 256/8, but you can also express it as: ValueLayout.JAVA_INT.byteSize() * 8 MemorySegment segment = arena.allocate(32); segment.set(ValueLayout.JAVA_INT, 0, 11); segment.set(ValueLayout.JAVA_INT, 4, 21); segment.set(ValueLayout.JAVA_INT, 8, 12); segment.set(ValueLayout.JAVA_INT, 12, 7); segment.set(ValueLayout.JAVA_INT, 16, 33); segment.set(ValueLayout.JAVA_INT, 20, 1); segment.set(ValueLayout.JAVA_INT, 24, 3); segment.set(ValueLayout.JAVA_INT, 28, 6); v0 = IntVector.fromMemorySegment(VS256, segment, 0, ByteOrder.nativeOrder()); } System.out.println("v0: " + Arrays.toString(v0.toIntArray())); IntVector v1; try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocate(32); segment.setAtIndex(ValueLayout.JAVA_INT, 0, 11); segment.setAtIndex(ValueLayout.JAVA_INT, 1, 21); segment.setAtIndex(ValueLayout.JAVA_INT, 2, 12); segment.setAtIndex(ValueLayout.JAVA_INT, 3, 7); segment.setAtIndex(ValueLayout.JAVA_INT, 4, 33); segment.setAtIndex(ValueLayout.JAVA_INT, 5, 1); segment.setAtIndex(ValueLayout.JAVA_INT, 6, 3); segment.setAtIndex(ValueLayout.JAVA_INT, 7, 6); v1 = IntVector.fromMemorySegment(VS256, segment, 0, ByteOrder.nativeOrder()); } System.out.println("v1: " + Arrays.toString(v1.toIntArray())); IntVector v2; try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocateFrom( // JDK 22 ValueLayout.JAVA_INT, 11, 21, 12, 7, 33, 1, 3, 6); v2 = IntVector.fromMemorySegment(VS256, segment, 0, ByteOrder.nativeOrder()); } System.out.println("v2: " + Arrays.toString(v2.toIntArray())); IntVector v3; try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocateFrom( // JDK 22 ValueLayout.JAVA_INT, new int[]{11, 21, 12, 7, 33, 1, 3, 6}); v3 = IntVector.fromMemorySegment(VS256, segment, 0, ByteOrder.nativeOrder()); } System.out.println("v3: " + Arrays.toString(v3.toIntArray())); // on-heap array MemorySegment segment = MemorySegment .ofArray(new int[]{11, 21, 12, 7, 33, 1, 3, 6}); System.out.println("On-heap, fifth element: " + segment.get(ValueLayout.JAVA_INT, 16)); System.out.println("On-heap, fifth element: " + segment.getAtIndex(ValueLayout.JAVA_INT, 4)); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 22/P144_EngagingJNI/src/main/java/modern/challenge/Main.java
Chapter07/JDK 22/P144_EngagingJNI/src/main/java/modern/challenge/Main.java
package modern.challenge; public class Main { static { System.loadLibrary("math"); } private native long sumTwoInt(int x, int y); public static void main(String[] args) { long result = new Main().sumTwoInt(3, 9); System.out.println("Result: " + result); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 22/P152_IntroSequenceLayout/src/main/java/modern/challenge/Main.java
Chapter07/JDK 22/P152_IntroSequenceLayout/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.lang.foreign.Arena; import java.lang.foreign.MemoryLayout; import java.lang.foreign.MemoryLayout.PathElement; import java.lang.foreign.MemorySegment; import java.lang.foreign.SequenceLayout; import java.lang.foreign.ValueLayout; import java.lang.invoke.VarHandle; public class Main { public static void main(String[] args) { System.out.println("Imitating a sequence layout: "); try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocate( ValueLayout.JAVA_DOUBLE.byteSize() * 10, ValueLayout.JAVA_DOUBLE.byteAlignment()); for (int i = 0; i < 10; i++) { segment.setAtIndex(ValueLayout.JAVA_DOUBLE, i, Math.random()); } for (int i = 0; i < 10; i++) { System.out.printf("\nx = %.2f", segment.getAtIndex(ValueLayout.JAVA_DOUBLE, i)); } } System.out.println(); System.out.println("\nSingle sequence layout using path element: "); SequenceLayout seq = MemoryLayout.sequenceLayout( 10, ValueLayout.JAVA_DOUBLE); // VarHandle[varType=double, coord=[interface java.lang.foreign.MemorySegment, long, long]] VarHandle sphandle = seq.varHandle(PathElement.sequenceElement()); try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocate(seq); System.out.println("\nSequence size in bytes: " + segment.byteSize()); for (int i = 0; i < seq.elementCount(); i++) { sphandle.set(segment, 0L, i, Math.random()); } for (int i = 0; i < seq.elementCount(); i++) { System.out.printf("\nx = %.2f", sphandle.get(segment, 0L, i)); } } System.out.println(); System.out.println("\nSingle sequence layout using array element: "); // VarHandle[varType=double, coord=[interface java.lang.foreign.MemorySegment, long, long]] VarHandle sahandle = ValueLayout.JAVA_DOUBLE.arrayElementVarHandle(); try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocate(seq); System.out.println("\nSequence size in bytes: " + segment.byteSize()); for (int i = 0; i < seq.elementCount(); i++) { sahandle.set(segment, 0L, i, Math.random()); } for (int i = 0; i < seq.elementCount(); i++) { System.out.printf("\nx = %.2f", sahandle.get(segment, 0L, i)); } } System.out.println(); System.out.println("\nNested sequence layout using path element: "); SequenceLayout nestedseq = MemoryLayout.sequenceLayout(5, MemoryLayout.sequenceLayout(10, ValueLayout.JAVA_DOUBLE)); // VarHandle[varType=double, coord=[interface java.lang.foreign.MemorySegment, long, long, long]] VarHandle nphandle = nestedseq.varHandle( PathElement.sequenceElement(), PathElement.sequenceElement()); try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocate(nestedseq); System.out.println("\nNested sequence size in bytes: " + segment.byteSize()); long outer = nestedseq.elementCount(); long inner = ((SequenceLayout) nestedseq.select(PathElement.sequenceElement())).elementCount(); for (int i = 0; i < outer; i++) { for (int j = 0; j < inner; j++) { nphandle.set(segment, 0L, i, j, Math.random()); } } for (int i = 0; i < outer; i++) { System.out.print("\n-----" + i + "-----"); for (int j = 0; j < inner; j++) { System.out.printf("\nx = %.2f", nphandle.get(segment, 0L, i, j)); } } } } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 22/P153_MemorySegmentAndStruct/src/main/java/modern/challenge/Main.java
Chapter07/JDK 22/P153_MemorySegmentAndStruct/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.lang.foreign.Arena; import java.lang.foreign.MemoryLayout; import java.lang.foreign.MemoryLayout.PathElement; import java.lang.foreign.MemorySegment; import java.lang.foreign.SequenceLayout; import java.lang.foreign.ValueLayout; import java.lang.invoke.VarHandle; public class Main { public static void main(String[] args) { try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocate( 2 * ValueLayout.JAVA_DOUBLE.byteSize() * 5, ValueLayout.JAVA_DOUBLE.byteAlignment()); System.out.println("\nSegment size in bytes: " + segment.byteSize()); for (int i = 0; i < 5; i++) { segment.setAtIndex(ValueLayout.JAVA_DOUBLE, i * 2, Math.random()); segment.setAtIndex(ValueLayout.JAVA_DOUBLE, i * 2 + 1, Math.random()); } for (int i = 0; i < 5; i++) { System.out.printf("\nx = %.2f", segment.getAtIndex(ValueLayout.JAVA_DOUBLE, i * 2)); System.out.printf("\ny = %.2f", segment.getAtIndex(ValueLayout.JAVA_DOUBLE, i * 2 + 1)); } } System.out.println(); SequenceLayout struct = MemoryLayout.sequenceLayout(5, MemoryLayout.structLayout( ValueLayout.JAVA_DOUBLE.withName("x"), ValueLayout.JAVA_DOUBLE.withName("y"))); // VarHandle[varType=double, coord=[interface java.lang.foreign.MemorySegment, long, long]] VarHandle xHandle = struct.varHandle(PathElement.sequenceElement(), PathElement.groupElement("x")); // VarHandle[varType=double, coord=[interface java.lang.foreign.MemorySegment, long, long]] VarHandle yHandle = struct.varHandle(PathElement.sequenceElement(), PathElement.groupElement("y")); try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocate(struct); System.out.println("\nStruct size in bytes: " + segment.byteSize()); for (int i = 0; i < struct.elementCount(); i++) { xHandle.set(segment, 0L, i, Math.random()); yHandle.set(segment, 0L, i, Math.random()); } for (int i = 0; i < struct.elementCount(); i++) { System.out.printf("\nx = %.2f", xHandle.get(segment, 0L, i)); System.out.printf("\ny = %.2f", yHandle.get(segment, 0L, i)); } } // challenge yourself to fill with data the following layout SequenceLayout product = MemoryLayout.sequenceLayout(3, MemoryLayout.structLayout( ValueLayout.JAVA_INT.withName("price"), ValueLayout.JAVA_INT.withName("discount"), ValueLayout.JAVA_INT.withName("weight"), MemoryLayout.structLayout( ValueLayout.JAVA_INT.withName("quantity"), ValueLayout.JAVA_INT.withName("qrcode")).withName("detail") ).withName("info")); VarHandle priceHandle = product.varHandle( PathElement.sequenceElement(), PathElement.groupElement("price")); VarHandle discountHandle = product.varHandle( PathElement.sequenceElement(), PathElement.groupElement("discount")); VarHandle weightHandle = product.varHandle( PathElement.sequenceElement(), PathElement.groupElement("weight")); VarHandle quantityHandle = product.varHandle( PathElement.sequenceElement(), PathElement.groupElement("detail"), PathElement.groupElement("quantity")); VarHandle qrHandle = product.varHandle( PathElement.sequenceElement(), PathElement.groupElement("detail"), PathElement.groupElement("qrcode")); // add here the code for setting/getting data } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 22/P165_CallingGetpid/src/main/java/modern/challenge/Main.java
Chapter07/JDK 22/P165_CallingGetpid/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.lang.foreign.FunctionDescriptor; import java.lang.foreign.Linker; import java.lang.foreign.MemorySegment; import java.lang.foreign.SymbolLookup; import java.lang.foreign.ValueLayout; import java.lang.invoke.MethodHandle; public class Main { public static void main(String[] args) throws Throwable { // get the Linker of the underlying native platform // (operating system + processor that runs the JVM) Linker linker = Linker.nativeLinker(); // "_getpid" is part of the Universal C Runtime (UCRT) Library SymbolLookup libLookup = linker.defaultLookup(); // find the "_getpid" foreign function MemorySegment segmentGetpid = libLookup.find("_getpid").get(); // create a method handle for "_getpid" MethodHandle func = linker.downcallHandle(segmentGetpid, FunctionDescriptor.of(ValueLayout.JAVA_INT)); // invoke the foreign function, "_getpid" and get the result int result = (int) func.invokeExact(); System.out.println(result); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 22/P151_MemorySegmentAndAddress/src/main/java/modern/challenge/Main.java
Chapter07/JDK 22/P151_MemorySegmentAndAddress/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.lang.foreign.Arena; import java.lang.foreign.MemorySegment; import java.lang.foreign.ValueLayout; public class Main { public static void main(String[] args) { try (Arena arena = Arena.ofConfined()) { MemorySegment addrs = arena.allocate(ValueLayout.ADDRESS, 3); // JDK 22 MemorySegment i1 = arena.allocateFrom(ValueLayout.JAVA_INT, 1); // JDK 22 MemorySegment i2 = arena.allocateFrom(ValueLayout.JAVA_INT, 3); // JDK 22 MemorySegment i3 = arena.allocateFrom(ValueLayout.JAVA_INT, 2); // JDK 22 addrs.setAtIndex(ValueLayout.ADDRESS, 0, i1); addrs.setAtIndex(ValueLayout.ADDRESS, 1, i2); addrs.setAtIndex(ValueLayout.ADDRESS, 2, i3); MemorySegment addr1 = addrs.getAtIndex(ValueLayout.ADDRESS, 0); MemorySegment addr2 = addrs.getAtIndex(ValueLayout.ADDRESS, 1); MemorySegment addr3 = addrs.getAtIndex(ValueLayout.ADDRESS, 2); // addr1.get(ValueLayout.JAVA_INT, 0); // DON'T DO THIS! System.out.println("Value at address1: " + MemorySegment.ofAddress( addr1.address()).reinterpret(ValueLayout.JAVA_INT.byteSize()).get(ValueLayout.JAVA_INT, 0)); System.out.println("Value at address2: " + MemorySegment.ofAddress( addr2.address()).reinterpret(ValueLayout.JAVA_INT.byteSize()).get(ValueLayout.JAVA_INT, 0)); System.out.println("Value at address3: " + MemorySegment.ofAddress( addr3.address()).reinterpret(ValueLayout.JAVA_INT.byteSize()).get(ValueLayout.JAVA_INT, 0)); System.out.println(); System.out.println("Address 1: " + addr1 + " | " + i1.address() + " Value 1: " + i1.getAtIndex(ValueLayout.JAVA_INT, 0)); System.out.println("Address 2: " + addr2 + " | " + i2.address() + " Value 2: " + i2.getAtIndex(ValueLayout.JAVA_INT, 0)); System.out.println("Address 3: " + addr3 + " | " + i3.address() + " Value 3: " + i3.getAtIndex(ValueLayout.JAVA_INT, 0)); System.out.println(); // check as long System.out.println(addr1.address() == i1.address()); // check as MemorySegments System.out.println(addr1.equals(i1)); System.out.println(); System.out.println("i1: " + i1.get(ValueLayout.JAVA_INT, 0)); System.out.println("i2: " + i2.get(ValueLayout.JAVA_INT, 0)); System.out.println("i3: " + i3.get(ValueLayout.JAVA_INT, 0)); long i2Addr = i2.address(); i2 = MemorySegment.ofAddress(i3.address()).reinterpret(ValueLayout.JAVA_INT.byteSize()); i3 = MemorySegment.ofAddress(i2Addr).reinterpret(ValueLayout.JAVA_INT.byteSize()); System.out.println(); System.out.println("i1: " + i1.get(ValueLayout.JAVA_INT, 0)); System.out.println("i2: " + i2.get(ValueLayout.JAVA_INT, 0)); System.out.println("i3: " + i3.get(ValueLayout.JAVA_INT, 0)); } } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 22/P156_CopyingSlicingMemorySegments/src/main/java/module-info.java
Chapter07/JDK 22/P156_CopyingSlicingMemorySegments/src/main/java/module-info.java
module P156_VectorTerminology { requires jdk.incubator.vector; }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 22/P156_CopyingSlicingMemorySegments/src/main/java/modern/challenge/Main.java
Chapter07/JDK 22/P156_CopyingSlicingMemorySegments/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.lang.foreign.Arena; import java.lang.foreign.MemorySegment; import java.lang.foreign.ValueLayout; import java.nio.ByteOrder; import java.util.Arrays; import jdk.incubator.vector.IntVector; import jdk.incubator.vector.VectorSpecies; public class Main { public static void main(String[] args) { VectorSpecies<Integer> VS128 = IntVector.SPECIES_128; IntVector v1, v2, v3; int[] jv1, jv2, jv3; try (Arena arena = Arena.ofConfined()) { MemorySegment srcSegment = arena.allocateFrom( ValueLayout.JAVA_INT, 1, 2, 3, 4, -1, -1, -1, 52, 22, 33, -1, -1, -1, -1, -1, 4); MemorySegment copySegment = srcSegment.copyFrom(srcSegment); System.out.println("Data: " + Arrays.toString(copySegment.toArray(ValueLayout.JAVA_INT))); System.out.println("\nCopying ...\n"); MemorySegment dstSegment1 = arena.allocate(ValueLayout.JAVA_INT, 8); MemorySegment.copy(srcSegment, 32, dstSegment1, 0, 4 * 8); System.out.println("Destination segment (1): " + Arrays.toString(dstSegment1.toArray(ValueLayout.JAVA_INT))); int[] dstArray = new int[8]; MemorySegment.copy(srcSegment, ValueLayout.JAVA_INT, 32, dstArray, 0, 8); System.out.println("Destination array (2): " + Arrays.toString(dstArray)); int[] srcArray = new int[]{10, 44, 2, 6, 55, 65, 7, 89}; MemorySegment dstSegment2 = arena.allocate(ValueLayout.JAVA_INT, 16); MemorySegment.copy(srcArray, 0, dstSegment2, ValueLayout.JAVA_INT, 32, 8); System.out.println("Destination segment (3): " + Arrays.toString(dstSegment2.toArray(ValueLayout.JAVA_INT))); // MemorySegment.copy(srcSegment, 32, dstSegment2, 0, 32); MemorySegment.copy(srcSegment, ValueLayout.JAVA_INT, 32, dstSegment2, ValueLayout.JAVA_INT, 0, 8); System.out.println("Destination segment (4): " + Arrays.toString(dstSegment2.toArray(ValueLayout.JAVA_INT))); System.out.println("\nSlicing ...\n"); v1 = IntVector.fromMemorySegment(VS128, srcSegment.asSlice(0, 16), 0, ByteOrder.nativeOrder()); v2 = IntVector.fromMemorySegment(VS128, srcSegment.asSlice(28, 12), 0L, ByteOrder.nativeOrder(), VS128.indexInRange(0, 3)); v3 = IntVector.fromMemorySegment(VS128, srcSegment.asSlice(60), 0, ByteOrder.nativeOrder(), VS128.indexInRange(0, 1)); System.out.println("v1: " + Arrays.toString(v1.toIntArray())); System.out.println("v2: " + Arrays.toString(v2.toIntArray())); System.out.println("v3: " + Arrays.toString(v3.toIntArray())); jv1 = srcSegment.asSlice(0, 16).toArray(ValueLayout.JAVA_INT); jv2 = srcSegment.asSlice(28, 12).toArray(ValueLayout.JAVA_INT); jv3 = srcSegment.asSlice(60).toArray(ValueLayout.JAVA_INT); System.out.println(); System.out.println("jv1: " + Arrays.toString(jv1)); System.out.println("jv2: " + Arrays.toString(jv2)); System.out.println("jv3: " + Arrays.toString(jv3)); } // asOverlappingSlice() try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocateFrom(ValueLayout.JAVA_INT, new int[]{1, 2, 3, 4, 6, 8, 4, 5, 3}); MemorySegment subsegment = segment.asSlice(12); int[] subarray = segment.asOverlappingSlice(subsegment) .orElse(MemorySegment.NULL).toArray(ValueLayout.JAVA_INT); System.out.println("\nSub-array: " + Arrays.toString(subarray)); } } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 22/P160_IntroLayoutReshaping/src/main/java/modern/challenge/Main.java
Chapter07/JDK 22/P160_IntroLayoutReshaping/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.lang.foreign.Arena; import java.lang.foreign.MemoryLayout; import java.lang.foreign.MemoryLayout.PathElement; import java.lang.foreign.MemorySegment; import java.lang.foreign.SequenceLayout; import java.lang.foreign.ValueLayout; import java.lang.invoke.VarHandle; public class Main { public static void main(String[] args) { SequenceLayout innerSeq = MemoryLayout.sequenceLayout(5, ValueLayout.JAVA_DOUBLE); SequenceLayout outerSeq = MemoryLayout.sequenceLayout(10, innerSeq); VarHandle handle = outerSeq.varHandle( PathElement.sequenceElement(), PathElement.sequenceElement()); try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocate(outerSeq); System.out.println("Outer: " + outerSeq.elementCount()); System.out.println("Inner: " + innerSeq.elementCount()); for (int i = 0; i < outerSeq.elementCount(); i++) { for (int j = 0; j < innerSeq.elementCount(); j++) { handle.set(segment, 0L, i, j, Math.random()); } } for (int i = 0; i < outerSeq.elementCount(); i++) { System.out.print("\n-----" + i + "-----"); for (int j = 0; j < innerSeq.elementCount(); j++) { System.out.printf("\nx = %.2f", handle.get(segment, 0L, i, j)); } } } // reshape SequenceLayout reshaped = outerSeq.reshape(25, 2); VarHandle rhandle = reshaped.varHandle( PathElement.sequenceElement(), PathElement.sequenceElement()); try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocate(reshaped); System.out.println("\n\nReshaped outerSeq: " + reshaped.elementCount()); System.out.println("Reshaped innerSeq: " + ((SequenceLayout) reshaped.select( PathElement.sequenceElement())).elementCount()); long outerSeqCount = reshaped.elementCount(); long innerSeqCount = ((SequenceLayout) reshaped.select( PathElement.sequenceElement())).elementCount(); for (int i = 0; i < outerSeqCount; i++) { for (int j = 0; j < innerSeqCount; j++) { rhandle.set(segment, 0L, i, j, Math.random()); } } for (int i = 0; i < outerSeqCount; i++) { System.out.print("\n-----" + i + "-----"); for (int j = 0; j < innerSeqCount; j++) { System.out.printf("\nx = %.2f", rhandle.get(segment, 0L, i, j)); } } } } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 22/P154_MemorySegmentAndUnion/src/main/java/modern/challenge/Main.java
Chapter07/JDK 22/P154_MemorySegmentAndUnion/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.lang.foreign.Arena; import java.lang.foreign.MemoryLayout; import java.lang.foreign.MemoryLayout.PathElement; import java.lang.foreign.MemorySegment; import java.lang.foreign.UnionLayout; import java.lang.foreign.ValueLayout; import java.lang.invoke.VarHandle; public class Main { public static void main(String[] args) { try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocate( ValueLayout.JAVA_DOUBLE.byteSize(), ValueLayout.JAVA_DOUBLE.byteAlignment()); System.out.println("\nUnion size in bytes: " + segment.byteSize()); segment.setAtIndex(ValueLayout.JAVA_DOUBLE, 0, 500.99); System.out.printf("\nprice = %.2f", segment.getAtIndex(ValueLayout.JAVA_DOUBLE, 0)); segment.setAtIndex(ValueLayout.JAVA_INT, 0, 101000); System.out.printf("\nprice (garbage value) = %.2f", segment.getAtIndex(ValueLayout.JAVA_DOUBLE, 0)); System.out.println("\nsku = " + segment.getAtIndex(ValueLayout.JAVA_INT, 0)); segment.setAtIndex(ValueLayout.JAVA_DOUBLE, 0, 500.99); System.out.printf("\nprice = %.2f", segment.getAtIndex(ValueLayout.JAVA_DOUBLE, 0)); System.out.println("\nsku (garbage value) = " + segment.getAtIndex(ValueLayout.JAVA_INT, 0)); } System.out.println(); UnionLayout union = MemoryLayout.unionLayout( ValueLayout.JAVA_DOUBLE.withName("price"), ValueLayout.JAVA_INT.withName("sku")); VarHandle pHandle = union.varHandle(PathElement.groupElement("price")); VarHandle sHandle = union.varHandle(PathElement.groupElement("sku")); try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocate(union); System.out.println("\nUnion size in bytes: " + segment.byteSize()); pHandle.set(segment, 0L, 500.99); System.out.printf("\nprice = %.2f", pHandle.get(segment, 0L)); sHandle.set(segment, 0L, 101000); System.out.printf("\nprice (garbage value) = %.2f", pHandle.get(segment, 0L)); System.out.println("\nsku = " + sHandle.get(segment, 0L)); pHandle.set(segment, 0L, 500.99); System.out.printf("\nprice = %.2f", pHandle.get(segment, 0L)); System.out.println("\nsku (garbage value) = " + sHandle.get(segment, 0L)); } } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 22/P162_IntroMemorySegmentViewVarHandle/src/main/java/modern/challenge/Main.java
Chapter07/JDK 22/P162_IntroMemorySegmentViewVarHandle/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.lang.foreign.Arena; import java.lang.foreign.MemorySegment; import java.lang.foreign.ValueLayout; import java.lang.invoke.MethodHandles; import java.lang.invoke.VarHandle; public class Main { public static void main(String[] args) { try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocate(ValueLayout.JAVA_INT); System.out.println("Segment size: " + segment.byteSize()); // VarHandle[varType=int, coord=[interface java.lang.foreign.MemorySegment]] VarHandle pathhandle = ValueLayout.JAVA_INT.varHandle(); pathhandle.set(segment, 0L, 25); System.out.println("Value: " + pathhandle.get(segment, 0L)); // VarHandle[varType=int, coord=[interface java.lang.foreign.MemorySegment, long]] VarHandle arrhandle = ValueLayout.JAVA_INT.arrayElementVarHandle(); arrhandle.set(segment,0L, 0, 50); System.out.println("Value: " + arrhandle.get(segment, 0L, 0L)); // NO LOGER AVAILABLE IN JDK 22 // VarHandle[varType=int, coord=[interface java.lang.foreign.MemorySegment, long]] /* VarHandle viewhandle = MethodHandles.memorySegmentViewVarHandle(ValueLayout.JAVA_INT); // insert the coordinates viewhandle = MethodHandles.insertCoordinates(viewhandle, 1, 0); viewhandle.set(segment, 75); System.out.println("Value: " + viewhandle.get(segment)); */ } } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 22/P145_EngagingJNA/src/main/java/modern/challenge/SimpleMath.java
Chapter07/JDK 22/P145_EngagingJNA/src/main/java/modern/challenge/SimpleMath.java
package modern.challenge; import com.sun.jna.Library; public interface SimpleMath extends Library { long sumTwoInt(int x, int y); }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 22/P145_EngagingJNA/src/main/java/modern/challenge/Main.java
Chapter07/JDK 22/P145_EngagingJNA/src/main/java/modern/challenge/Main.java
package modern.challenge; import com.sun.jna.Library; import com.sun.jna.Native; import com.sun.jna.NativeLibrary; import com.sun.jna.Platform; import com.sun.jna.win32.StdCallFunctionMapper; import java.lang.reflect.Method; import java.util.Map; @SuppressWarnings("unchecked") public class Main { private static final Map MAPPINGS; static { MAPPINGS = Map.of( Library.OPTION_FUNCTION_MAPPER, new StdCallFunctionMapper() { Map<String, String> methodNames = Map.of("sumTwoInt", "_Z9sumTwoIntii"); @Override public String getFunctionName(NativeLibrary library, Method method) { String methodName = method.getName(); return methodNames.get(methodName); } }); } public static void main(String[] args) { System.setProperty("jna.library.path", "./jna/cpp"); SimpleMath math = Native.load(Platform.isWindows() ? "math" : "NOT_WINDOWS", SimpleMath.class, MAPPINGS); long result = math.sumTwoInt(3, 9); System.out.println("Result: " + result); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 22/P161_IntroLayoutSpreader/src/main/java/modern/challenge/Main.java
Chapter07/JDK 22/P161_IntroLayoutSpreader/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.lang.foreign.Arena; import java.lang.foreign.MemoryLayout; import java.lang.foreign.MemoryLayout.PathElement; import java.lang.foreign.MemorySegment; import java.lang.foreign.SequenceLayout; import java.lang.foreign.ValueLayout; import java.lang.invoke.MethodHandle; import java.lang.invoke.VarHandle; public class Main { public static void main(String[] args) throws Throwable { SequenceLayout innerSeq = MemoryLayout.sequenceLayout(5, ValueLayout.JAVA_DOUBLE); SequenceLayout outerSeq = MemoryLayout.sequenceLayout(10, innerSeq); VarHandle handle = outerSeq.varHandle( PathElement.sequenceElement(), PathElement.sequenceElement()); try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocate(outerSeq); System.out.println("Outer: " + outerSeq.elementCount()); System.out.println("Inner: " + innerSeq.elementCount()); for (int i = 0; i < outerSeq.elementCount(); i++) { for (int j = 0; j < innerSeq.elementCount(); j++) { handle.set(segment, 0L, i, j, Math.random()); } } for (int i = 0; i < outerSeq.elementCount(); i++) { System.out.print("\n-----" + i + "-----"); for (int j = 0; j < innerSeq.elementCount(); j++) { System.out.printf("\nx = %.5f", handle.get(segment, 0L, i, j)); } } MethodHandle mHandle = outerSeq.sliceHandle( PathElement.sequenceElement(), PathElement.sequenceElement() ); System.out.println(); System.out.println(); // no spreader // MemorySegment ms = (MemorySegment) mHandle.invokeExact(segment, 7L, 3L); // with spreader MemorySegment ms = (MemorySegment) mHandle .asSpreader(Long[].class, 2).invokeExact(segment, 0L, new Long[]{7L, 3L}); System.out.println(ms.get(ValueLayout.JAVA_DOUBLE, 0)); } } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 21/P157_WorkingWithSlicingAllocator/src/main/java/modern/challenge/Main.java
Chapter07/JDK 21/P157_WorkingWithSlicingAllocator/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.lang.foreign.Arena; import java.lang.foreign.MemorySegment; import java.lang.foreign.SegmentAllocator; import java.lang.foreign.ValueLayout; import java.util.Arrays; public class Main { public static void main(String[] args) { int[] arr1 = new int[]{1, 2, 3, 4, 5, 6}; int[] arr2 = new int[]{7, 8, 9}; int[] arr3 = new int[]{10, 11, 12, 13, 14}; try (Arena arena = Arena.ofConfined()) { MemorySegment segment1 = arena.allocateArray(ValueLayout.JAVA_INT, arr1); MemorySegment segment2 = arena.allocateArray(ValueLayout.JAVA_INT, arr2); MemorySegment segment3 = arena.allocateArray(ValueLayout.JAVA_INT, arr3); System.out.println("Segment 1: " + Arrays.toString(segment1.toArray(ValueLayout.JAVA_INT))); System.out.println("Segment 2: " + Arrays.toString(segment2.toArray(ValueLayout.JAVA_INT))); System.out.println("Segment 3: " + Arrays.toString(segment3.toArray(ValueLayout.JAVA_INT))); } System.out.println(); // using a pre-allocated segment that doesn't fit all data try (Arena arena = Arena.ofConfined()) { // it should be 10 * 4 + 4 * 4 SegmentAllocator allocator = SegmentAllocator.slicingAllocator(arena.allocate(10 * 4)); MemorySegment segment1 = allocator.allocateArray(ValueLayout.JAVA_INT, arr1); MemorySegment segment2 = allocator.allocateArray(ValueLayout.JAVA_INT, arr2); MemorySegment segment3 = allocator.allocateArray(ValueLayout.JAVA_INT, arr3); System.out.println("Segment 1: " + Arrays.toString(segment1.toArray(ValueLayout.JAVA_INT))); System.out.println("Segment 2: " + Arrays.toString(segment2.toArray(ValueLayout.JAVA_INT))); System.out.println("Segment 3: " + Arrays.toString(segment3.toArray(ValueLayout.JAVA_INT))); } catch (IndexOutOfBoundsException e) { System.out.println("There is not enough memory to fit all data"); // handle exception } } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 21/P167_CallingModf/src/main/java/modern/challenge/Main.java
Chapter07/JDK 21/P167_CallingModf/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.lang.foreign.Arena; import java.lang.foreign.FunctionDescriptor; import java.lang.foreign.Linker; import java.lang.foreign.MemorySegment; import java.lang.foreign.SymbolLookup; import java.lang.foreign.ValueLayout; import java.lang.invoke.MethodHandle; public class Main { public static void main(String[] args) throws Throwable { double x = 89.76655; Linker linker = Linker.nativeLinker(); SymbolLookup libLookup = linker.defaultLookup(); try (Arena arena = Arena.ofConfined()) { MemorySegment segmentModf = libLookup.find("modf").get(); MethodHandle func = linker.downcallHandle(segmentModf, FunctionDescriptor.of( ValueLayout.JAVA_DOUBLE, ValueLayout.JAVA_DOUBLE, ValueLayout.ADDRESS)); MemorySegment segmentIntptr = arena.allocate(ValueLayout.JAVA_DOUBLE); double fractional = (double) func.invokeExact(x, segmentIntptr); System.out.println("Fractional part: " + fractional + " Integer part: " + segmentIntptr.get(ValueLayout.JAVA_DOUBLE, 0)); } } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 21/P155_IntroPaddingLayout/src/main/java/modern/challenge/Main.java
Chapter07/JDK 21/P155_IntroPaddingLayout/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.lang.foreign.Arena; import java.lang.foreign.MemoryLayout; import java.lang.foreign.MemoryLayout.PathElement; import java.lang.foreign.MemorySegment; import java.lang.foreign.SequenceLayout; import java.lang.foreign.StructLayout; import java.lang.foreign.ValueLayout; import java.lang.invoke.VarHandle; public class Main { public static void main(String[] args) { System.out.println("No padding struct"); System.out.println("--------------------------------------------------"); StructLayout npStruct = MemoryLayout.structLayout( ValueLayout.JAVA_INT.withName("x"), ValueLayout.JAVA_INT.withName("y") ); VarHandle xnHandle = npStruct.varHandle(PathElement.groupElement("x")); VarHandle ynHandle = npStruct.varHandle(PathElement.groupElement("y")); try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocate(npStruct); System.out.println("\nNo padding struct size in bytes: " + segment.byteSize()); xnHandle.set(segment, 23); // offset 0 ynHandle.set(segment, 54); // offset 4 System.out.println(); System.out.println("Offset 0: " + segment.get(ValueLayout.JAVA_INT, 0)); System.out.println("Offset 4: " + segment.get(ValueLayout.JAVA_INT, 4)); } System.out.println("--------------------------------------------------"); System.out.println("\nStruct with two padding of 4 bytes"); System.out.println("--------------------------------------------------"); StructLayout wpStruct = MemoryLayout.structLayout( MemoryLayout.paddingLayout(4), // 4 bytes ValueLayout.JAVA_INT.withName("x"), MemoryLayout.paddingLayout(4), // 4 bytes ValueLayout.JAVA_INT.withName("y") ); VarHandle xpHandle = wpStruct.varHandle(PathElement.groupElement("x")); VarHandle ypHandle = wpStruct.varHandle(PathElement.groupElement("y")); try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocate(wpStruct); System.out.println("\nStruct with padding size in bytes: " + segment.byteSize()); xpHandle.set(segment, 23); // offset 4 ypHandle.set(segment, 54); // offset 12 System.out.println(); System.out.println("Offset 0: " + segment.get(ValueLayout.JAVA_INT, 0)); System.out.println("Offset 4: " + segment.get(ValueLayout.JAVA_INT, 4)); System.out.println("Offset 8: " + segment.get(ValueLayout.JAVA_INT, 8)); System.out.println("Offset 12: " + segment.get(ValueLayout.JAVA_INT, 12)); } System.out.println("--------------------------------------------------"); MemorySegment segmenta = Arena.ofAuto().allocate(12); segmenta.set(ValueLayout.JAVA_INT, 0, 1000); segmenta.set(ValueLayout.JAVA_CHAR, 4, 'a'); segmenta.set(ValueLayout.JAVA_INT, 8, 2000); // try it out with 6 instead of 8 System.out.println("\nStruct with padding for fixing alignment"); System.out.println("----------------------Case 1----------------------"); StructLayout product1 = MemoryLayout.structLayout( ValueLayout.JAVA_INT.withName("sku"), ValueLayout.JAVA_CHAR.withName("energy"), ValueLayout.JAVA_BYTE.withName("weight")); System.out.println("Size: " + product1.byteSize()); System.out.println("Alignment: " + product1.byteAlignment()); System.out.println("Sku byte offset: " + product1.byteOffset(PathElement.groupElement("sku"))); System.out.println("Energy byte offset: " + product1.byteOffset(PathElement.groupElement("energy"))); System.out.println("Weight byte offset: " + product1.byteOffset(PathElement.groupElement("weight"))); VarHandle spHandle1 = product1.varHandle(PathElement.groupElement("sku")); VarHandle epHandle1 = product1.varHandle(PathElement.groupElement("energy")); VarHandle wpHandle1 = product1.varHandle(PathElement.groupElement("weight")); try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocate(product1); spHandle1.set(segment, 10102); epHandle1.set(segment, 'D'); wpHandle1.set(segment, (byte) 12); System.out.println(); System.out.println("Sku: " + spHandle1.get(segment)); System.out.println("Energy: " + epHandle1.get(segment)); System.out.println("Weight: " + wpHandle1.get(segment)); } System.out.println("--------------------------------------------------"); System.out.println(); System.out.println("----------------------Case 2----------------------"); StructLayout product2 = MemoryLayout.structLayout( ValueLayout.JAVA_CHAR.withName("energy"), MemoryLayout.paddingLayout(2), ValueLayout.JAVA_INT.withName("sku"), ValueLayout.JAVA_BYTE.withName("weight") ); System.out.println("Size: " + product2.byteSize()); System.out.println("Alignment: " + product2.byteAlignment()); System.out.println("Energy byte offset: " + product2.byteOffset(PathElement.groupElement("energy"))); System.out.println("Sku byte offset: " + product2.byteOffset(PathElement.groupElement("sku"))); System.out.println("Weight byte offset: " + product2.byteOffset(PathElement.groupElement("weight"))); // use arrayElementVarHandle() VarHandle erHandle2 = ValueLayout.JAVA_CHAR.arrayElementVarHandle(); VarHandle srHandle2 = ValueLayout.JAVA_INT.arrayElementVarHandle(); VarHandle wrHandle2 = ValueLayout.JAVA_BYTE.arrayElementVarHandle(); try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocate(product2); erHandle2.set(segment, 0, 'D'); srHandle2.set(segment, 1, 10102); wrHandle2.set(segment, 2, (byte) 12); System.out.println(); System.out.println("Energy: " + erHandle2.get(segment, 0)); System.out.println("Sku: " + srHandle2.get(segment, 1)); System.out.println("Weight: " + wrHandle2.get(segment, 2)); } // use PathElement VarHandle epHandle2 = product2.varHandle(PathElement.groupElement("energy")); VarHandle spHandle2 = product2.varHandle(PathElement.groupElement("sku")); VarHandle wpHandle2 = product2.varHandle(PathElement.groupElement("weight")); try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocate(product2); epHandle2.set(segment, 'D'); spHandle2.set(segment, 10102); wpHandle2.set(segment, (byte) 12); System.out.println(); System.out.println("Energy: " + epHandle2.get(segment)); System.out.println("Sku: " + spHandle2.get(segment)); System.out.println("Weight: " + wpHandle2.get(segment)); } System.out.println("--------------------------------------------------"); System.out.println(); System.out.println("----------------------Case 3----------------------"); SequenceLayout product3 = MemoryLayout.sequenceLayout( 2, MemoryLayout.structLayout( ValueLayout.JAVA_CHAR.withName("energy"), MemoryLayout.paddingLayout(2), ValueLayout.JAVA_INT.withName("sku"), ValueLayout.JAVA_BYTE.withName("weight"), MemoryLayout.paddingLayout(3) )); System.out.println("Size: " + product3.byteSize()); System.out.println("Alignment: " + product3.byteAlignment()); System.out.println("Energy byte offset (0): " + product3.byteOffset( PathElement.sequenceElement(0), PathElement.groupElement("energy"))); System.out.println("Energy byte offset (1): " + product3.byteOffset( PathElement.sequenceElement(1), PathElement.groupElement("energy"))); System.out.println("Sku byte offset (0): " + product3.byteOffset( PathElement.sequenceElement(0), PathElement.groupElement("sku"))); System.out.println("Sku byte offset (1): " + product3.byteOffset( PathElement.sequenceElement(1), PathElement.groupElement("sku"))); System.out.println("Weight byte offset (0): " + product3.byteOffset( PathElement.sequenceElement(0), PathElement.groupElement("weight"))); System.out.println("Weight byte offset (1): " + product3.byteOffset( PathElement.sequenceElement(1), PathElement.groupElement("weight"))); // use arrayElementVarHandle() VarHandle erHandle3 = ValueLayout.JAVA_CHAR.arrayElementVarHandle(2); VarHandle srHandle3 = ValueLayout.JAVA_INT.arrayElementVarHandle(2); VarHandle wrHandle3 = ValueLayout.JAVA_BYTE.arrayElementVarHandle(2); try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocate(product3); erHandle3.set(segment, 0, 0, 'D'); srHandle3.set(segment, 1, 0, 10102); wrHandle3.set(segment, 2, 0, (byte) 12); erHandle3.set(segment, 0, 1, 'A'); srHandle3.set(segment, 1, 1, 454402); wrHandle3.set(segment, 2, 1, (byte) 9); System.out.println(); System.out.println("Energy (1): " + erHandle3.get(segment, 0, 0)); System.out.println("Sku (1): " + srHandle3.get(segment, 1, 0)); System.out.println("Weight (1): " + wrHandle3.get(segment, 2, 0)); System.out.println(); System.out.println("Energy (2): " + erHandle3.get(segment, 0, 1)); System.out.println("Sku (2): " + srHandle3.get(segment, 1, 1)); System.out.println("Weight (2): " + wrHandle3.get(segment, 2, 1)); } // use PathElement VarHandle epHandle3 = product3.varHandle( PathElement.sequenceElement(), PathElement.groupElement("energy")); VarHandle spHandle3 = product3.varHandle( PathElement.sequenceElement(), PathElement.groupElement("sku")); VarHandle wpHandle3 = product3.varHandle( PathElement.sequenceElement(), PathElement.groupElement("weight")); try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocate(product3); epHandle3.set(segment, 0, 'D'); spHandle3.set(segment, 0, 10102); wpHandle3.set(segment, 0, (byte) 12); epHandle3.set(segment, 1, 'A'); spHandle3.set(segment, 1, 454402); wpHandle3.set(segment, 1, (byte) 9); System.out.println(); System.out.println("Energy (1): " + epHandle3.get(segment, 0)); System.out.println("Sku (1): " + spHandle3.get(segment, 0)); System.out.println("Weight (1): " + wpHandle3.get(segment, 0)); System.out.println(); System.out.println("Energy (2): " + epHandle3.get(segment, 1)); System.out.println("Sku (2): " + spHandle3.get(segment, 1)); System.out.println("Weight (2): " + wpHandle3.get(segment, 1)); } System.out.println("--------------------------------------------------"); System.out.println(); System.out.println("----------------------Case 4----------------------"); StructLayout product4 = MemoryLayout.structLayout( ValueLayout.JAVA_BYTE.withName("weight"), MemoryLayout.paddingLayout(1), ValueLayout.JAVA_CHAR.withName("energy"), ValueLayout.JAVA_INT.withName("sku") ); System.out.println("Size: " + product4.byteSize()); System.out.println("Alignment: " + product4.byteAlignment()); System.out.println("Weight byte offset: " + product4.byteOffset(PathElement.groupElement("weight"))); System.out.println("Energy byte offset: " + product4.byteOffset(PathElement.groupElement("energy"))); System.out.println("Sku byte offset: " + product4.byteOffset(PathElement.groupElement("sku"))); /* challenge yourself to use arrayElementVarHandle() or PathElement */ System.out.println("--------------------------------------------------"); System.out.println(); System.out.println("----------------------Case 5----------------------"); StructLayout product5 = MemoryLayout.structLayout( ValueLayout.JAVA_INT.withName("sku"), ValueLayout.JAVA_BYTE.withName("weight"), MemoryLayout.paddingLayout(1), ValueLayout.JAVA_CHAR.withName("energy") ); System.out.println("Size: " + product5.byteSize()); System.out.println("Alignment: " + product5.byteAlignment()); System.out.println("Sku byte offset: " + product5.byteOffset(PathElement.groupElement("sku"))); System.out.println("Weight byte offset: " + product5.byteOffset(PathElement.groupElement("weight"))); System.out.println("Energy byte offset: " + product5.byteOffset(PathElement.groupElement("energy"))); /* challenge yourself to use arrayElementVarHandle() or PathElement */ System.out.println("--------------------------------------------------"); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 21/P163_StreamingMemorySegment/src/main/java/modern/challenge/Main.java
Chapter07/JDK 21/P163_StreamingMemorySegment/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.lang.foreign.Arena; import java.lang.foreign.MemoryLayout; import java.lang.foreign.MemoryLayout.PathElement; import java.lang.foreign.MemorySegment; import java.lang.foreign.SequenceLayout; import java.lang.foreign.ValueLayout; import java.lang.invoke.MethodHandle; import java.lang.invoke.VarHandle; import java.util.Arrays; public class Main { public static void main(String[] args) throws Throwable { SequenceLayout xy = MemoryLayout.sequenceLayout(2, MemoryLayout.structLayout( ValueLayout.JAVA_INT.withName("x"), ValueLayout.JAVA_INT.withName("y") )); VarHandle xHandle = xy.varHandle( PathElement.sequenceElement(), PathElement.groupElement("x")); VarHandle yHandle = xy.varHandle( PathElement.sequenceElement(), PathElement.groupElement("y")); try (Arena arena = Arena.ofShared()) { MemorySegment segment = arena.allocate(xy); xHandle.set(segment, 0, 5); yHandle.set(segment, 0, 9); xHandle.set(segment, 1, 6); yHandle.set(segment, 1, 8); // sum everything int sum1 = segment.elements(xy) .map(t -> t.toArray(ValueLayout.JAVA_INT)) .flatMapToInt(t -> Arrays.stream(t)) .sum(); int sum2 = segment.elements(ValueLayout.JAVA_INT).parallel() .mapToInt(s -> s.get(ValueLayout.JAVA_INT, 0)) .sum(); System.out.println("Sum everything: " + sum1 + " " + sum2); // sum only the frist pair of x, y MethodHandle xyHandle = xy.sliceHandle(PathElement.sequenceElement()); MemorySegment subsegment = (MemorySegment) xyHandle.invoke(segment, 0); int sum3 = subsegment.elements(ValueLayout.JAVA_INT).parallel() .mapToInt(s -> s.get(ValueLayout.JAVA_INT, 0)) .sum(); System.out.println("Sum the first pair of (x, y): " + sum3); // sum y from the first pair with the second pair (x, y) var sum4 = segment.elements(xy).parallel() .map(t -> t.asSlice(4).toArray(ValueLayout.JAVA_INT)) // by offset 4 we skip the first x .flatMapToInt(t -> Arrays.stream(t)) .sum(); System.out.println("Sum y from the first pair with the second pair (x, y): " + sum4); } } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 21/P164_ArenaMappedMemorySegment/src/main/java/modern/challenge/MappedArena.java
Chapter07/JDK 21/P164_ArenaMappedMemorySegment/src/main/java/modern/challenge/MappedArena.java
package modern.challenge; import java.io.IOException; import java.lang.foreign.Arena; import java.lang.foreign.MemorySegment; import java.nio.channels.FileChannel; import static java.nio.channels.FileChannel.MapMode.READ_WRITE; import java.nio.file.Path; import static java.nio.file.StandardOpenOption.CREATE_NEW; import static java.nio.file.StandardOpenOption.READ; import static java.nio.file.StandardOpenOption.SPARSE; import static java.nio.file.StandardOpenOption.WRITE; public class MappedArena implements Arena { private final String fileName; private final Arena shared; public MappedArena(String fileName) { if (fileName == null) { throw new IllegalArgumentException("The file name cannot be null"); } this.fileName = fileName; this.shared = Arena.ofShared(); } @Override public MemorySegment allocate(long byteSize, long byteAlignment) { try (FileChannel file = FileChannel.open( Path.of(fileName + System.currentTimeMillis() + ".txt"), CREATE_NEW, SPARSE, READ, WRITE)) { return file.map(READ_WRITE, 0, byteSize, shared); } catch (IOException e) { throw new RuntimeException(e); } } @Override public MemorySegment.Scope scope() { return shared.scope(); } @Override public void close() { shared.close(); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 21/P164_ArenaMappedMemorySegment/src/main/java/modern/challenge/Main.java
Chapter07/JDK 21/P164_ArenaMappedMemorySegment/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.io.IOException; import java.lang.foreign.Arena; import java.lang.foreign.MemorySegment; public class Main { public static void main(String[] args) throws IOException { try (Arena arena = new MappedArena("readme")) { MemorySegment segment1 = arena.allocate(100); MemorySegment segment2 = arena.allocate(50); segment1.setUtf8String(0, "Hello"); segment2.setUtf8String(0, "World"); System.out.println(segment1.getUtf8String(0) + " " + segment2.getUtf8String(0)); } System.out.println("\n\nYou should find the files on disk in the project's root"); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 21/P159_IntroLayoutFlatenning/src/main/java/modern/challenge/Main.java
Chapter07/JDK 21/P159_IntroLayoutFlatenning/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.lang.foreign.Arena; import java.lang.foreign.MemoryLayout; import java.lang.foreign.MemoryLayout.PathElement; import java.lang.foreign.MemorySegment; import java.lang.foreign.SequenceLayout; import java.lang.foreign.ValueLayout; import java.lang.invoke.VarHandle; public class Main { public static void main(String[] args) { SequenceLayout innerSeq = MemoryLayout.sequenceLayout(5, ValueLayout.JAVA_DOUBLE); SequenceLayout outerSeq = MemoryLayout.sequenceLayout(10, innerSeq); VarHandle handle = outerSeq.varHandle( PathElement.sequenceElement(), PathElement.sequenceElement()); try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocate(outerSeq); System.out.println("Outer: " + outerSeq.elementCount()); System.out.println("Inner: " + innerSeq.elementCount()); for (int i = 0; i < outerSeq.elementCount(); i++) { for (int j = 0; j < innerSeq.elementCount(); j++) { handle.set(segment, i, j, Math.random()); } } for (int i = 0; i < outerSeq.elementCount(); i++) { System.out.print("\n-----" + i + "-----"); for (int j = 0; j < innerSeq.elementCount(); j++) { System.out.printf("\nx = %.2f", handle.get(segment, i, j)); } } // flatten and dispay System.out.println("\n\nFlatten and dispay:"); SequenceLayout flatten = outerSeq.flatten(); VarHandle fhandle = flatten.varHandle(PathElement.sequenceElement()); for (int i = 0; i < flatten.elementCount(); i++) { System.out.printf("\nx = %.2f", fhandle.get(segment, i)); } } // flatten and reallocate System.out.println("\n\nFlatten and reallocate:"); SequenceLayout flatten = outerSeq.flatten(); VarHandle fhandle = flatten.varHandle(PathElement.sequenceElement()); try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocate(flatten); System.out.println("Element count: " + flatten.elementCount()); for (int i = 0; i < flatten.elementCount(); i++) { fhandle.set(segment, i, Math.random()); } for (int i = 0; i < flatten.elementCount(); i++) { System.out.printf("\nx = %.2f", fhandle.get(segment, i)); } } } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 21/P166_CallingSumTwoInt/src/main/java/modern/challenge/Main.java
Chapter07/JDK 21/P166_CallingSumTwoInt/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.lang.foreign.Arena; import java.lang.foreign.FunctionDescriptor; import java.lang.foreign.Linker; import java.lang.foreign.MemorySegment; import java.lang.foreign.SymbolLookup; import java.lang.foreign.ValueLayout; import java.lang.invoke.MethodHandle; import java.nio.file.Path; import java.nio.file.Paths; public class Main { public static void main(String[] args) throws Throwable { Linker linker = Linker.nativeLinker(); Path path = Paths.get("lib/cpp/math.dll"); try (Arena arena = Arena.ofConfined()) { SymbolLookup libLookup = SymbolLookup.libraryLookup(path, arena); MemorySegment segmentSumTwoInt = libLookup.find("_Z9sumTwoIntii").get(); MethodHandle func = linker.downcallHandle(segmentSumTwoInt, FunctionDescriptor.of(ValueLayout.JAVA_LONG, ValueLayout.JAVA_INT, ValueLayout.JAVA_INT)); long result = (long) func.invokeExact(3, 9); System.out.println(result); } } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 21/P158_IntroSliceHandle/src/main/java/modern/challenge/Main.java
Chapter07/JDK 21/P158_IntroSliceHandle/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.lang.foreign.Arena; import java.lang.foreign.MemoryLayout; import java.lang.foreign.MemoryLayout.PathElement; import java.lang.foreign.MemorySegment; import java.lang.foreign.SequenceLayout; import java.lang.foreign.ValueLayout; import java.lang.invoke.MethodHandle; import java.lang.invoke.VarHandle; import java.util.Arrays; public class Main { public static void main(String[] args) throws Throwable { SequenceLayout innerSeq = MemoryLayout.sequenceLayout(5, ValueLayout.JAVA_DOUBLE); SequenceLayout outerSeq = MemoryLayout.sequenceLayout(10, innerSeq); VarHandle handle = outerSeq.varHandle( PathElement.sequenceElement(), PathElement.sequenceElement()); try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocate(outerSeq); System.out.println("Outer: " + outerSeq.elementCount()); System.out.println("Inner: " + innerSeq.elementCount()); for (int i = 0; i < outerSeq.elementCount(); i++) { for (int j = 0; j < innerSeq.elementCount(); j++) { handle.set(segment, i, j, Math.random()); } } for (int i = 0; i < outerSeq.elementCount(); i++) { System.out.print("\n-----" + i + "-----"); for (int j = 0; j < innerSeq.elementCount(); j++) { System.out.printf("\nx = %.5f", handle.get(segment, i, j)); } } MethodHandle mHandle = outerSeq.sliceHandle( PathElement.sequenceElement() ); System.out.println(); System.out.println("\n The third sequence of 10:" + Arrays.toString( ((MemorySegment) mHandle.invoke(segment, 3)) .toArray(ValueLayout.JAVA_DOUBLE))); } } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 21/P168_CallingStrcat/src/main/java/modern/challenge/Main.java
Chapter07/JDK 21/P168_CallingStrcat/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.lang.foreign.Arena; import java.lang.foreign.FunctionDescriptor; import java.lang.foreign.Linker; import java.lang.foreign.MemorySegment; import java.lang.foreign.SymbolLookup; import java.lang.foreign.ValueLayout; import java.lang.invoke.MethodHandle; public class Main { public static void main(String[] args) throws Throwable { String strDestination = "Hello "; String strSource = "World"; Linker linker = Linker.nativeLinker(); SymbolLookup libLookup = linker.defaultLookup(); try (Arena arena = Arena.ofConfined()) { MemorySegment segmentStrcat = libLookup.find("strcat").get(); MethodHandle func = linker.downcallHandle(segmentStrcat, FunctionDescriptor.ofVoid( ValueLayout.ADDRESS, ValueLayout.ADDRESS)); MemorySegment segmentStrSource = arena.allocate(strSource.length() + 1); segmentStrSource.setUtf8String(0, strSource); MemorySegment segmentStrDestination = arena.allocate( strSource.length() + 1 + strDestination.length() + 1); segmentStrDestination.setUtf8String(0, strDestination); func.invokeExact(segmentStrDestination, segmentStrSource); System.out.println(segmentStrDestination.getUtf8String(0)); } } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 21/P164_MappedMemorySegment/src/main/java/modern/challenge/Main.java
Chapter07/JDK 21/P164_MappedMemorySegment/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.io.IOException; import java.lang.foreign.Arena; import java.lang.foreign.MemorySegment; import java.nio.channels.FileChannel; import static java.nio.channels.FileChannel.MapMode.READ_WRITE; import java.nio.file.Path; import static java.nio.file.StandardOpenOption.CREATE; import static java.nio.file.StandardOpenOption.CREATE_NEW; import static java.nio.file.StandardOpenOption.READ; import static java.nio.file.StandardOpenOption.SPARSE; import static java.nio.file.StandardOpenOption.WRITE; public class Main { public static void main(String[] args) throws IOException { try (FileChannel file = FileChannel.open( Path.of("readme.txt"), CREATE, READ, WRITE); Arena arena = Arena.ofConfined()) { MemorySegment segment = file.map(READ_WRITE, 0, 1048576, arena); // 1 Megabyte = 1048576 bytes // 1 Gigabyte = 1073741824 bytes // write the data segment.setUtf8String(0, "This is a readme file ..."); segment.setUtf8String(1048576/2, "Here is the middle of the file ..."); segment.setUtf8String(1048576-32, "Here is the end of the file ..."); // read some data System.out.println(segment.getUtf8String(1048576/2)); } try (FileChannel file = FileChannel.open( Path.of("sparse_readme.txt"), CREATE_NEW, SPARSE, READ, WRITE); Arena arena = Arena.ofConfined()) { MemorySegment segment = file.map(READ_WRITE, 0, 1048576, arena); // 1 Megabyte = 1048576 bytes // 1 Gigabyte = 1073741824 bytes // write the data segment.setUtf8String(0, "This is a readme file ..."); segment.setUtf8String(1048576/2, "Here is the middle of the file ..."); segment.setUtf8String(1048576-32, "Here is the end of the file ..."); // read some data System.out.println(segment.getUtf8String(0)); } System.out.println("\n\nYou should find the files on disk in the project's root"); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 21/P149_ArenaMemorySegment/src/main/java/modern/challenge/Main.java
Chapter07/JDK 21/P149_ArenaMemorySegment/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.lang.foreign.Arena; import java.lang.foreign.MemorySegment; import java.lang.foreign.ValueLayout; public class Main { public static void main(String[] args) { // globalSegment1 and globalSegment2 are never deallocated MemorySegment globalSegment1 = Arena.global().allocate(8); MemorySegment globalSegment2 = Arena.global().allocate( ValueLayout.JAVA_DOUBLE.byteSize(), ValueLayout.JAVA_DOUBLE.byteAlignment()); // autoSegment1 and autoSegment2 are automatically managed by the garbage collector MemorySegment autoSegment1 = Arena.ofAuto().allocate(8); MemorySegment autoSegment2 = Arena.ofAuto().allocate( ValueLayout.JAVA_DOUBLE.byteSize(), ValueLayout.JAVA_DOUBLE.byteAlignment()); // arenaSegment1 and arenaSegment2 are available only in the try-with-resource block try (Arena arena = Arena.ofConfined()) { MemorySegment arenaSegment1 = arena.allocate(8); MemorySegment arenaSegment2 = arena.allocate( ValueLayout.JAVA_DOUBLE.byteSize(), ValueLayout.JAVA_DOUBLE.byteAlignment()); } try (Arena arena = Arena.ofConfined()) { System.out.println("Arena is alive? " + arena.scope().isAlive()); // already has arena's scope MemorySegment segment1i1 = arena.allocate(4); MemorySegment segment1i2 = arena.allocate(ValueLayout.JAVA_INT.byteSize()); MemorySegment segment1i3 = arena.allocate(ValueLayout.JAVA_INT, Integer.MAX_VALUE); MemorySegment segment1d = arena.allocate(ValueLayout.JAVA_DOUBLE.byteSize(), ValueLayout.JAVA_DOUBLE.byteAlignment()); MemorySegment segment1a1 = arena.allocate(ValueLayout.JAVA_CHAR); MemorySegment segment1a2 = arena.allocate(ValueLayout.JAVA_CHAR, 'a'); MemorySegment segment1s = arena.allocateUtf8String("abcd"); segment1i1.set(ValueLayout.JAVA_INT, 0, Integer.MAX_VALUE); segment1i2.set(ValueLayout.JAVA_INT, 0, Integer.MAX_VALUE); segment1d.set(ValueLayout.JAVA_DOUBLE, 0, Double.MIN_VALUE); segment1a1.setAtIndex(ValueLayout.JAVA_CHAR, 0, 'a'); MemorySegment segment2i1 = arena.allocate(4); MemorySegment segment2i2 = arena.allocate(ValueLayout.JAVA_INT); MemorySegment segment2d = arena.allocate( ValueLayout.JAVA_DOUBLE.byteSize(), ValueLayout.JAVA_DOUBLE.byteAlignment()); MemorySegment segment2a1 = arena.allocate(2); MemorySegment segment2a2 = arena.allocate( ValueLayout.JAVA_CHAR.byteSize()); MemorySegment segment2s = arena.allocate(5); // "abcd".length() + 1 = 5 segment2i1.set(ValueLayout.JAVA_INT, 0, Integer.MAX_VALUE); segment2i2.setAtIndex(ValueLayout.JAVA_INT, 0, Integer.MAX_VALUE); segment2d.set(ValueLayout.JAVA_DOUBLE, 0, Double.MAX_VALUE); segment2a1.set(ValueLayout.JAVA_CHAR, 0, 'a'); segment2a2.set(ValueLayout.JAVA_CHAR, 0, 'a'); segment2s.setUtf8String(0, "abcd"); System.out.println("Segment 1i1: " + segment1i1); System.out.println("Segment 1i1 content: " + segment1i1.get(ValueLayout.JAVA_INT, 0)); System.out.println("Segment 1i2: " + segment1i2); System.out.println("Segment 1i2 content: " + segment1i2.get(ValueLayout.JAVA_INT, 0)); System.out.println("Segment 1i3: " + segment1i3); System.out.println("Segment 1i3 content: " + segment1i3.get(ValueLayout.JAVA_INT, 0)); System.out.println("Segment 2i1: " + segment2i1); System.out.println("Segment 2i1 content: " + segment2i1.get(ValueLayout.JAVA_INT, 0)); System.out.println("Segment 2i2: " + segment2i2); System.out.println("Segment 2i2 content: " + segment2i2.get(ValueLayout.JAVA_INT, 0)); System.out.println("Segment 1s: " + segment1s); System.out.println("Segment 1s content: " + segment1s.getUtf8String(0)); System.out.println("Segment 2s: " + segment2s); System.out.println("Segment 2s content: " + segment2s.getUtf8String(0)); System.out.println("Segment 1d: " + segment1d); System.out.println("Segment 1d content: " + segment1d.get(ValueLayout.JAVA_DOUBLE, 0)); System.out.println("Segment 2d: " + segment2d); System.out.println("Segment 2d content: " + segment2d.get(ValueLayout.JAVA_DOUBLE, 0)); System.out.println("Segment 1a1: " + segment1a1); System.out.println("Segment 1a1 content: " + segment1a1.get(ValueLayout.JAVA_CHAR, 0)); System.out.println("Segment 1a2: " + segment1a2); System.out.println("Segment 1a2 content: " + segment1a2.get(ValueLayout.JAVA_CHAR, 0)); System.out.println("Segment 2a1: " + segment2a1); System.out.println("Segment 2a1 content: " + segment2a1.getAtIndex(ValueLayout.JAVA_CHAR, 0)); System.out.println("Segment 2a2: " + segment2a2); System.out.println("Segment 2a2 content: " + segment2a2.getAtIndex(ValueLayout.JAVA_CHAR, 0)); } } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 21/P146_EngagingJNR/src/main/java/modern/challenge/SimpleMath.java
Chapter07/JDK 21/P146_EngagingJNR/src/main/java/modern/challenge/SimpleMath.java
package modern.challenge; import jnr.ffi.annotations.IgnoreError; public interface SimpleMath { @IgnoreError long sumTwoInt(int x, int y); }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 21/P146_EngagingJNR/src/main/java/modern/challenge/Main.java
Chapter07/JDK 21/P146_EngagingJNR/src/main/java/modern/challenge/Main.java
package modern.challenge; import jnr.ffi.LibraryLoader; import jnr.ffi.Platform; import jnr.ffi.provider.FFIProvider; public class Main { public static void main(String[] args) { LibraryLoader<SimpleMath> loader = FFIProvider.getSystemProvider() .createLibraryLoader(SimpleMath.class) .search("./jnr/cpp") .map("sumTwoInt", "_Z9sumTwoIntii"); if (Platform.getNativePlatform().getOS() == Platform.OS.WINDOWS) { SimpleMath simpleMath = loader.load("math"); long result = simpleMath.sumTwoInt(3, 9); System.out.println("Result: " + result); } } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 21/P150_MemorySegmentAndArray/src/main/java/module-info.java
Chapter07/JDK 21/P150_MemorySegmentAndArray/src/main/java/module-info.java
module P150_VectorTerminology { requires jdk.incubator.vector; }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 21/P150_MemorySegmentAndArray/src/main/java/modern/challenge/Main.java
Chapter07/JDK 21/P150_MemorySegmentAndArray/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.lang.foreign.Arena; import java.lang.foreign.MemorySegment; import java.lang.foreign.ValueLayout; import java.nio.ByteOrder; import java.util.Arrays; import jdk.incubator.vector.IntVector; import jdk.incubator.vector.VectorSpecies; public class Main { public static void main(String[] args) { VectorSpecies<Integer> VS256 = IntVector.SPECIES_256; IntVector v0; try (Arena arena = Arena.ofConfined()) { // 32 = 256/8, but you can also express it as: ValueLayout.JAVA_INT.byteSize() * 8 MemorySegment segment = arena.allocate(32); segment.set(ValueLayout.JAVA_INT, 0, 11); segment.set(ValueLayout.JAVA_INT, 4, 21); segment.set(ValueLayout.JAVA_INT, 8, 12); segment.set(ValueLayout.JAVA_INT, 12, 7); segment.set(ValueLayout.JAVA_INT, 16, 33); segment.set(ValueLayout.JAVA_INT, 20, 1); segment.set(ValueLayout.JAVA_INT, 24, 3); segment.set(ValueLayout.JAVA_INT, 28, 6); v0 = IntVector.fromMemorySegment(VS256, segment, 0, ByteOrder.nativeOrder()); } System.out.println("v0: " + Arrays.toString(v0.toIntArray())); IntVector v1; try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocate(32); segment.setAtIndex(ValueLayout.JAVA_INT, 0, 11); segment.setAtIndex(ValueLayout.JAVA_INT, 1, 21); segment.setAtIndex(ValueLayout.JAVA_INT, 2, 12); segment.setAtIndex(ValueLayout.JAVA_INT, 3, 7); segment.setAtIndex(ValueLayout.JAVA_INT, 4, 33); segment.setAtIndex(ValueLayout.JAVA_INT, 5, 1); segment.setAtIndex(ValueLayout.JAVA_INT, 6, 3); segment.setAtIndex(ValueLayout.JAVA_INT, 7, 6); v1 = IntVector.fromMemorySegment(VS256, segment, 0, ByteOrder.nativeOrder()); } System.out.println("v1: " + Arrays.toString(v1.toIntArray())); IntVector v2; try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocateArray( ValueLayout.JAVA_INT, 11, 21, 12, 7, 33, 1, 3, 6); v2 = IntVector.fromMemorySegment(VS256, segment, 0, ByteOrder.nativeOrder()); } System.out.println("v2: " + Arrays.toString(v2.toIntArray())); IntVector v3; try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocateArray( ValueLayout.JAVA_INT, new int[]{11, 21, 12, 7, 33, 1, 3, 6}); v3 = IntVector.fromMemorySegment(VS256, segment, 0, ByteOrder.nativeOrder()); } System.out.println("v3: " + Arrays.toString(v3.toIntArray())); // on-heap array MemorySegment segment = MemorySegment .ofArray(new int[]{11, 21, 12, 7, 33, 1, 3, 6}); System.out.println("On-heap, fifth element: " + segment.get(ValueLayout.JAVA_INT, 16)); System.out.println("On-heap, fifth element: " + segment.getAtIndex(ValueLayout.JAVA_INT, 4)); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 21/P144_EngagingJNI/src/main/java/modern/challenge/Main.java
Chapter07/JDK 21/P144_EngagingJNI/src/main/java/modern/challenge/Main.java
package modern.challenge; public class Main { static { System.loadLibrary("math"); } private native long sumTwoInt(int x, int y); public static void main(String[] args) { long result = new Main().sumTwoInt(3, 9); System.out.println("Result: " + result); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 21/P152_IntroSequenceLayout/src/main/java/modern/challenge/Main.java
Chapter07/JDK 21/P152_IntroSequenceLayout/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.lang.foreign.Arena; import java.lang.foreign.MemoryLayout; import java.lang.foreign.MemoryLayout.PathElement; import java.lang.foreign.MemorySegment; import java.lang.foreign.SequenceLayout; import java.lang.foreign.ValueLayout; import java.lang.invoke.VarHandle; public class Main { public static void main(String[] args) { System.out.println("Imitating a sequence layout: "); try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocate( ValueLayout.JAVA_DOUBLE.byteSize() * 10, ValueLayout.JAVA_DOUBLE.byteAlignment()); for (int i = 0; i < 10; i++) { segment.setAtIndex(ValueLayout.JAVA_DOUBLE, i, Math.random()); } for (int i = 0; i < 10; i++) { System.out.printf("\nx = %.2f", segment.getAtIndex(ValueLayout.JAVA_DOUBLE, i)); } } System.out.println(); System.out.println("\nSingle sequence layout using path element: "); SequenceLayout seq = MemoryLayout.sequenceLayout( 10, ValueLayout.JAVA_DOUBLE); // VarHandle[varType=double, coord=[interface java.lang.foreign.MemorySegment, long]] VarHandle sphandle = seq.varHandle(PathElement.sequenceElement()); try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocate(seq); System.out.println("\nSequence size in bytes: " + segment.byteSize()); for (int i = 0; i < seq.elementCount(); i++) { sphandle.set(segment, i, Math.random()); } for (int i = 0; i < seq.elementCount(); i++) { System.out.printf("\nx = %.2f", sphandle.get(segment, i)); } } System.out.println(); System.out.println("\nSingle sequence layout using array element: "); // VarHandle[varType=double, coord=[interface java.lang.foreign.MemorySegment, long]] VarHandle sahandle = ValueLayout.JAVA_DOUBLE.arrayElementVarHandle(); try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocate(seq); System.out.println("\nSequence size in bytes: " + segment.byteSize()); for (int i = 0; i < seq.elementCount(); i++) { sahandle.set(segment, i, Math.random()); } for (int i = 0; i < seq.elementCount(); i++) { System.out.printf("\nx = %.2f", sahandle.get(segment, i)); } } System.out.println(); System.out.println("\nNested sequence layout using path element: "); SequenceLayout nestedseq = MemoryLayout.sequenceLayout(5, MemoryLayout.sequenceLayout(10, ValueLayout.JAVA_DOUBLE)); // VarHandle[varType=double, coord=[interface java.lang.foreign.MemorySegment, long, long]] VarHandle nphandle = nestedseq.varHandle( PathElement.sequenceElement(), PathElement.sequenceElement()); try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocate(nestedseq); System.out.println("\nNested sequence size in bytes: " + segment.byteSize()); long outer = nestedseq.elementCount(); long inner = ((SequenceLayout) nestedseq.select(PathElement.sequenceElement())).elementCount(); for (int i = 0; i < outer; i++) { for (int j = 0; j < inner; j++) { nphandle.set(segment, i, j, Math.random()); } } for (int i = 0; i < outer; i++) { System.out.print("\n-----" + i + "-----"); for (int j = 0; j < inner; j++) { System.out.printf("\nx = %.2f", nphandle.get(segment, i, j)); } } } System.out.println(); System.out.println("\nNested sequence layout using array element: "); try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocate(nestedseq); System.out.println("\nNested sequence size in bytes: " + segment.byteSize()); // VarHandle[varType=double, coord=[interface java.lang.foreign.MemorySegment, long, long, long]] VarHandle nahandle = ValueLayout.JAVA_DOUBLE.arrayElementVarHandle(5, 10); for (int i = 0; i < 5; i++) { for (int j = 0; j < 10; j++) { nahandle.set(segment, 0, i, j, Math.random()); } } for (int i = 0; i < 5; i++) { System.out.print("\n-----" + i + "-----"); for (int j = 0; j < 10; j++) { System.out.printf("\nx = %.2f", nahandle.get(segment, 0, i, j)); } } } } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 21/P153_MemorySegmentAndStruct/src/main/java/modern/challenge/Main.java
Chapter07/JDK 21/P153_MemorySegmentAndStruct/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.lang.foreign.Arena; import java.lang.foreign.MemoryLayout; import java.lang.foreign.MemoryLayout.PathElement; import java.lang.foreign.MemorySegment; import java.lang.foreign.SequenceLayout; import java.lang.foreign.ValueLayout; import java.lang.invoke.VarHandle; public class Main { public static void main(String[] args) { try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocate( 2 * ValueLayout.JAVA_DOUBLE.byteSize() * 5, ValueLayout.JAVA_DOUBLE.byteAlignment()); System.out.println("\nSegment size in bytes: " + segment.byteSize()); for (int i = 0; i < 5; i++) { segment.setAtIndex(ValueLayout.JAVA_DOUBLE, i * 2, Math.random()); segment.setAtIndex(ValueLayout.JAVA_DOUBLE, i * 2 + 1, Math.random()); } for (int i = 0; i < 5; i++) { System.out.printf("\nx = %.2f", segment.getAtIndex(ValueLayout.JAVA_DOUBLE, i * 2)); System.out.printf("\ny = %.2f", segment.getAtIndex(ValueLayout.JAVA_DOUBLE, i * 2 + 1)); } } System.out.println(); SequenceLayout struct = MemoryLayout.sequenceLayout(5, MemoryLayout.structLayout( ValueLayout.JAVA_DOUBLE.withName("x"), ValueLayout.JAVA_DOUBLE.withName("y"))); // VarHandle[varType=double, coord=[interface java.lang.foreign.MemorySegment, long]] VarHandle xHandle = struct.varHandle(PathElement.sequenceElement(), PathElement.groupElement("x")); // VarHandle[varType=double, coord=[interface java.lang.foreign.MemorySegment, long]] VarHandle yHandle = struct.varHandle(PathElement.sequenceElement(), PathElement.groupElement("y")); try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocate(struct); System.out.println("\nStruct size in bytes: " + segment.byteSize()); for (int i = 0; i < struct.elementCount(); i++) { xHandle.set(segment, i, Math.random()); yHandle.set(segment, i, Math.random()); } for (int i = 0; i < struct.elementCount(); i++) { System.out.printf("\nx = %.2f", xHandle.get(segment, i)); System.out.printf("\ny = %.2f", yHandle.get(segment, i)); } } // challenge yourself to fill with data the following layout SequenceLayout product = MemoryLayout.sequenceLayout(3, MemoryLayout.structLayout( ValueLayout.JAVA_INT.withName("price"), ValueLayout.JAVA_INT.withName("discount"), ValueLayout.JAVA_INT.withName("weight"), MemoryLayout.structLayout( ValueLayout.JAVA_INT.withName("quantity"), ValueLayout.JAVA_INT.withName("qrcode")).withName("detail") ).withName("info")); VarHandle priceHandle = product.varHandle( PathElement.sequenceElement(), PathElement.groupElement("price")); VarHandle discountHandle = product.varHandle( PathElement.sequenceElement(), PathElement.groupElement("discount")); VarHandle weightHandle = product.varHandle( PathElement.sequenceElement(), PathElement.groupElement("weight")); VarHandle quantityHandle = product.varHandle( PathElement.sequenceElement(), PathElement.groupElement("detail"), PathElement.groupElement("quantity")); VarHandle qrHandle = product.varHandle( PathElement.sequenceElement(), PathElement.groupElement("detail"), PathElement.groupElement("qrcode")); // add here the code for setting/getting data } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 21/P165_CallingGetpid/src/main/java/modern/challenge/Main.java
Chapter07/JDK 21/P165_CallingGetpid/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.lang.foreign.FunctionDescriptor; import java.lang.foreign.Linker; import java.lang.foreign.MemorySegment; import java.lang.foreign.SymbolLookup; import java.lang.foreign.ValueLayout; import java.lang.invoke.MethodHandle; public class Main { public static void main(String[] args) throws Throwable { // get the Linker of the underlying native platform // (operating system + processor that runs the JVM) Linker linker = Linker.nativeLinker(); // "_getpid" is part of the Universal C Runtime (UCRT) Library SymbolLookup libLookup = linker.defaultLookup(); // find the "_getpid" foreign function MemorySegment segmentGetpid = libLookup.find("_getpid").get(); // create a method handle for "_getpid" MethodHandle func = linker.downcallHandle(segmentGetpid, FunctionDescriptor.of(ValueLayout.JAVA_INT)); // invoke the foreign function, "_getpid" and get the result int result = (int) func.invokeExact(); System.out.println(result); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 21/P151_MemorySegmentAndAddress/src/main/java/modern/challenge/Main.java
Chapter07/JDK 21/P151_MemorySegmentAndAddress/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.lang.foreign.Arena; import java.lang.foreign.MemorySegment; import java.lang.foreign.ValueLayout; public class Main { public static void main(String[] args) { try (Arena arena = Arena.ofConfined()) { MemorySegment addrs = arena.allocateArray(ValueLayout.ADDRESS, 3); MemorySegment i1 = arena.allocate(ValueLayout.JAVA_INT, 1); MemorySegment i2 = arena.allocate(ValueLayout.JAVA_INT, 3); MemorySegment i3 = arena.allocate(ValueLayout.JAVA_INT, 2); addrs.setAtIndex(ValueLayout.ADDRESS, 0, i1); addrs.setAtIndex(ValueLayout.ADDRESS, 1, i2); addrs.setAtIndex(ValueLayout.ADDRESS, 2, i3); MemorySegment addr1 = addrs.getAtIndex(ValueLayout.ADDRESS, 0); MemorySegment addr2 = addrs.getAtIndex(ValueLayout.ADDRESS, 1); MemorySegment addr3 = addrs.getAtIndex(ValueLayout.ADDRESS, 2); // addr1.get(ValueLayout.JAVA_INT, 0); // DON'T DO THIS! System.out.println("Value at address1: " + MemorySegment.ofAddress( addr1.address()).reinterpret(ValueLayout.JAVA_INT.byteSize()).get(ValueLayout.JAVA_INT, 0)); System.out.println("Value at address2: " + MemorySegment.ofAddress( addr2.address()).reinterpret(ValueLayout.JAVA_INT.byteSize()).get(ValueLayout.JAVA_INT, 0)); System.out.println("Value at address3: " + MemorySegment.ofAddress( addr3.address()).reinterpret(ValueLayout.JAVA_INT.byteSize()).get(ValueLayout.JAVA_INT, 0)); /* // Alternatively to the reinterpret() method we can use withTargetLayout(). AddressLayout intPointerLayout = ValueLayout.ADDRESS.withTargetLayout(ValueLayout.JAVA_INT); MemorySegment sgaddr1 = MemorySegment.ofAddress(addr1.address()).get(intPointerLayout, 0); System.out.println(sgaddr1.get(ValueLayout.JAVA_INT, 0)); */ System.out.println(); System.out.println("Address 1: " + addr1 + " | " + i1.address() + " Value 1: " + i1.getAtIndex(ValueLayout.JAVA_INT, 0)); System.out.println("Address 2: " + addr2 + " | " + i2.address() + " Value 2: " + i2.getAtIndex(ValueLayout.JAVA_INT, 0)); System.out.println("Address 3: " + addr3 + " | " + i3.address() + " Value 3: " + i3.getAtIndex(ValueLayout.JAVA_INT, 0)); System.out.println(); // check as long System.out.println(addr1.address() == i1.address()); // check as MemorySegments System.out.println(addr1.equals(i1)); System.out.println(); System.out.println("i1: " + i1.get(ValueLayout.JAVA_INT, 0)); System.out.println("i2: " + i2.get(ValueLayout.JAVA_INT, 0)); System.out.println("i3: " + i3.get(ValueLayout.JAVA_INT, 0)); long i2Addr = i2.address(); i2 = MemorySegment.ofAddress(i3.address()).reinterpret(ValueLayout.JAVA_INT.byteSize()); i3 = MemorySegment.ofAddress(i2Addr).reinterpret(ValueLayout.JAVA_INT.byteSize()); System.out.println(); System.out.println("i1: " + i1.get(ValueLayout.JAVA_INT, 0)); System.out.println("i2: " + i2.get(ValueLayout.JAVA_INT, 0)); System.out.println("i3: " + i3.get(ValueLayout.JAVA_INT, 0)); } } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 21/P171_JextractAndModf/src/main/java/modern/challenge/Main.java
Chapter07/JDK 21/P171_JextractAndModf/src/main/java/modern/challenge/Main.java
package modern.challenge; import static c.lib.math.math_h.modf; import java.lang.foreign.Arena; import java.lang.foreign.MemorySegment; import java.lang.foreign.ValueLayout; public class Main { public static void main(String[] args) { double x = 89.76655; try (Arena arena = Arena.ofConfined()) { MemorySegment segmentIntptr = arena.allocate(ValueLayout.JAVA_DOUBLE); double fractional = modf(x, segmentIntptr); System.out.println("Fractional part: " + fractional + " Integer part: " + segmentIntptr.get(ValueLayout.JAVA_DOUBLE, 0)); } } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 21/P171_JextractAndModf/src/main/java/c/lib/math/constants$38.java
Chapter07/JDK 21/P171_JextractAndModf/src/main/java/c/lib/math/constants$38.java
// Generated by jextract package c.lib.math; import java.lang.invoke.MethodHandle; import java.lang.invoke.VarHandle; import java.nio.ByteOrder; import java.lang.foreign.*; import static java.lang.foreign.ValueLayout.*; final class constants$38 { // Suppresses default constructor, ensuring non-instantiability. private constants$38() {} static final MethodHandle const$0 = RuntimeHelper.downcallHandle( "erfl", constants$10.const$2 ); static final MethodHandle const$1 = RuntimeHelper.downcallHandle( "erfc", constants$10.const$2 ); static final MethodHandle const$2 = RuntimeHelper.downcallHandle( "erfcf", constants$13.const$3 ); static final MethodHandle const$3 = RuntimeHelper.downcallHandle( "erfcl", constants$10.const$2 ); static final MethodHandle const$4 = RuntimeHelper.downcallHandle( "lgamma", constants$10.const$2 ); static final MethodHandle const$5 = RuntimeHelper.downcallHandle( "lgammaf", constants$13.const$3 ); }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 21/P171_JextractAndModf/src/main/java/c/lib/math/constants$47.java
Chapter07/JDK 21/P171_JextractAndModf/src/main/java/c/lib/math/constants$47.java
// Generated by jextract package c.lib.math; import java.lang.invoke.MethodHandle; import java.lang.invoke.VarHandle; import java.nio.ByteOrder; import java.lang.foreign.*; import static java.lang.foreign.ValueLayout.*; final class constants$47 { // Suppresses default constructor, ensuring non-instantiability. private constants$47() {} static final MethodHandle const$0 = RuntimeHelper.downcallHandle( "nan", constants$16.const$3 ); static final FunctionDescriptor const$1 = FunctionDescriptor.of(JAVA_FLOAT, RuntimeHelper.POINTER ); static final MethodHandle const$2 = RuntimeHelper.downcallHandle( "nanf", constants$47.const$1 ); static final MethodHandle const$3 = RuntimeHelper.downcallHandle( "nanl", constants$16.const$3 ); static final MethodHandle const$4 = RuntimeHelper.downcallHandle( "nextafter", constants$12.const$0 ); static final MethodHandle const$5 = RuntimeHelper.downcallHandle( "nextafterf", constants$26.const$5 ); }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 21/P171_JextractAndModf/src/main/java/c/lib/math/constants$52.java
Chapter07/JDK 21/P171_JextractAndModf/src/main/java/c/lib/math/constants$52.java
// Generated by jextract package c.lib.math; import java.lang.invoke.MethodHandle; import java.lang.invoke.VarHandle; import java.nio.ByteOrder; import java.lang.foreign.*; import static java.lang.foreign.ValueLayout.*; final class constants$52 { // Suppresses default constructor, ensuring non-instantiability. private constants$52() {} static final MethodHandle const$0 = RuntimeHelper.downcallHandle( "_isnanf", constants$23.const$2 ); static final MethodHandle const$1 = RuntimeHelper.downcallHandle( "_fpclassf", constants$23.const$2 ); static final MethodHandle const$2 = RuntimeHelper.downcallHandle( "_chgsignl", constants$10.const$2 ); static final MemorySegment const$3 = RuntimeHelper.CONSTANT_ALLOCATOR.allocateUtf8String("6.0.0"); static final MemorySegment const$4 = RuntimeHelper.CONSTANT_ALLOCATOR.allocateUtf8String("alpha"); static final MemorySegment const$5 = RuntimeHelper.CONSTANT_ALLOCATOR.allocateUtf8String("This function or variable may be unsafe, use _CRT_SECURE_NO_WARNINGS to disable deprecation"); }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 21/P171_JextractAndModf/src/main/java/c/lib/math/constants$11.java
Chapter07/JDK 21/P171_JextractAndModf/src/main/java/c/lib/math/constants$11.java
// Generated by jextract package c.lib.math; import java.lang.invoke.MethodHandle; import java.lang.invoke.VarHandle; import java.nio.ByteOrder; import java.lang.foreign.*; import static java.lang.foreign.ValueLayout.*; final class constants$11 { // Suppresses default constructor, ensuring non-instantiability. private constants$11() {} static final MethodHandle const$0 = RuntimeHelper.downcallHandle( "sinh", constants$10.const$2 ); static final MethodHandle const$1 = RuntimeHelper.downcallHandle( "cosh", constants$10.const$2 ); static final MethodHandle const$2 = RuntimeHelper.downcallHandle( "tanh", constants$10.const$2 ); static final MethodHandle const$3 = RuntimeHelper.downcallHandle( "asin", constants$10.const$2 ); static final MethodHandle const$4 = RuntimeHelper.downcallHandle( "acos", constants$10.const$2 ); static final MethodHandle const$5 = RuntimeHelper.downcallHandle( "atan", constants$10.const$2 ); }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 21/P171_JextractAndModf/src/main/java/c/lib/math/constants$12.java
Chapter07/JDK 21/P171_JextractAndModf/src/main/java/c/lib/math/constants$12.java
// Generated by jextract package c.lib.math; import java.lang.invoke.MethodHandle; import java.lang.invoke.VarHandle; import java.nio.ByteOrder; import java.lang.foreign.*; import static java.lang.foreign.ValueLayout.*; final class constants$12 { // Suppresses default constructor, ensuring non-instantiability. private constants$12() {} static final FunctionDescriptor const$0 = FunctionDescriptor.of(JAVA_DOUBLE, JAVA_DOUBLE, JAVA_DOUBLE ); static final MethodHandle const$1 = RuntimeHelper.downcallHandle( "atan2", constants$12.const$0 ); static final MethodHandle const$2 = RuntimeHelper.downcallHandle( "exp", constants$10.const$2 ); static final MethodHandle const$3 = RuntimeHelper.downcallHandle( "log", constants$10.const$2 ); static final MethodHandle const$4 = RuntimeHelper.downcallHandle( "log10", constants$10.const$2 ); static final MethodHandle const$5 = RuntimeHelper.downcallHandle( "pow", constants$12.const$0 ); }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 21/P171_JextractAndModf/src/main/java/c/lib/math/RuntimeHelper.java
Chapter07/JDK 21/P171_JextractAndModf/src/main/java/c/lib/math/RuntimeHelper.java
package c.lib.math; // Generated by jextract import java.lang.foreign.Linker; import java.lang.foreign.FunctionDescriptor; import java.lang.foreign.GroupLayout; import java.lang.foreign.SymbolLookup; import java.lang.foreign.MemoryLayout; import java.lang.foreign.MemorySegment; import java.lang.foreign.Arena; import java.lang.foreign.SegmentAllocator; import java.lang.foreign.ValueLayout; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; import java.io.File; import java.nio.file.Path; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Optional; import java.util.stream.Stream; import java.lang.foreign.AddressLayout; import java.lang.foreign.MemoryLayout; import static java.lang.foreign.Linker.*; import static java.lang.foreign.ValueLayout.*; final class RuntimeHelper { private static final Linker LINKER = Linker.nativeLinker(); private static final ClassLoader LOADER = RuntimeHelper.class.getClassLoader(); private static final MethodHandles.Lookup MH_LOOKUP = MethodHandles.lookup(); private static final SymbolLookup SYMBOL_LOOKUP; private static final SegmentAllocator THROWING_ALLOCATOR = (x, y) -> { throw new AssertionError("should not reach here"); }; static final AddressLayout POINTER = ValueLayout.ADDRESS.withTargetLayout(MemoryLayout.sequenceLayout(JAVA_BYTE)); final static SegmentAllocator CONSTANT_ALLOCATOR = (size, align) -> Arena.ofAuto().allocate(size, align); static { SymbolLookup loaderLookup = SymbolLookup.loaderLookup(); SYMBOL_LOOKUP = name -> loaderLookup.find(name).or(() -> LINKER.defaultLookup().find(name)); } // Suppresses default constructor, ensuring non-instantiability. private RuntimeHelper() {} static <T> T requireNonNull(T obj, String symbolName) { if (obj == null) { throw new UnsatisfiedLinkError("unresolved symbol: " + symbolName); } return obj; } static MemorySegment lookupGlobalVariable(String name, MemoryLayout layout) { return SYMBOL_LOOKUP.find(name) .map(s -> s.reinterpret(layout.byteSize())) .orElse(null); } static MethodHandle downcallHandle(String name, FunctionDescriptor fdesc) { return SYMBOL_LOOKUP.find(name). map(addr -> LINKER.downcallHandle(addr, fdesc)). orElse(null); } static MethodHandle downcallHandle(FunctionDescriptor fdesc) { return LINKER.downcallHandle(fdesc); } static MethodHandle downcallHandleVariadic(String name, FunctionDescriptor fdesc) { return SYMBOL_LOOKUP.find(name). map(addr -> VarargsInvoker.make(addr, fdesc)). orElse(null); } static MethodHandle upcallHandle(Class<?> fi, String name, FunctionDescriptor fdesc) { try { return MH_LOOKUP.findVirtual(fi, name, fdesc.toMethodType()); } catch (Throwable ex) { throw new AssertionError(ex); } } static <Z> MemorySegment upcallStub(MethodHandle fiHandle, Z z, FunctionDescriptor fdesc, Arena scope) { try { fiHandle = fiHandle.bindTo(z); return LINKER.upcallStub(fiHandle, fdesc, scope); } catch (Throwable ex) { throw new AssertionError(ex); } } static MemorySegment asArray(MemorySegment addr, MemoryLayout layout, int numElements, Arena arena) { return addr.reinterpret(numElements * layout.byteSize(), arena, null); } // Internals only below this point private static final class VarargsInvoker { private static final MethodHandle INVOKE_MH; private final MemorySegment symbol; private final FunctionDescriptor function; private VarargsInvoker(MemorySegment symbol, FunctionDescriptor function) { this.symbol = symbol; this.function = function; } static { try { INVOKE_MH = MethodHandles.lookup().findVirtual(VarargsInvoker.class, "invoke", MethodType.methodType(Object.class, SegmentAllocator.class, Object[].class)); } catch (ReflectiveOperationException e) { throw new RuntimeException(e); } } static MethodHandle make(MemorySegment symbol, FunctionDescriptor function) { VarargsInvoker invoker = new VarargsInvoker(symbol, function); MethodHandle handle = INVOKE_MH.bindTo(invoker).asCollector(Object[].class, function.argumentLayouts().size() + 1); MethodType mtype = MethodType.methodType(function.returnLayout().isPresent() ? carrier(function.returnLayout().get(), true) : void.class); for (MemoryLayout layout : function.argumentLayouts()) { mtype = mtype.appendParameterTypes(carrier(layout, false)); } mtype = mtype.appendParameterTypes(Object[].class); boolean needsAllocator = function.returnLayout().isPresent() && function.returnLayout().get() instanceof GroupLayout; if (needsAllocator) { mtype = mtype.insertParameterTypes(0, SegmentAllocator.class); } else { handle = MethodHandles.insertArguments(handle, 0, THROWING_ALLOCATOR); } return handle.asType(mtype); } static Class<?> carrier(MemoryLayout layout, boolean ret) { if (layout instanceof ValueLayout valueLayout) { return valueLayout.carrier(); } else if (layout instanceof GroupLayout) { return MemorySegment.class; } else { throw new AssertionError("Cannot get here!"); } } private Object invoke(SegmentAllocator allocator, Object[] args) throws Throwable { // one trailing Object[] int nNamedArgs = function.argumentLayouts().size(); assert(args.length == nNamedArgs + 1); // The last argument is the array of vararg collector Object[] unnamedArgs = (Object[]) args[args.length - 1]; int argsCount = nNamedArgs + unnamedArgs.length; Class<?>[] argTypes = new Class<?>[argsCount]; MemoryLayout[] argLayouts = new MemoryLayout[nNamedArgs + unnamedArgs.length]; int pos = 0; for (pos = 0; pos < nNamedArgs; pos++) { argLayouts[pos] = function.argumentLayouts().get(pos); } assert pos == nNamedArgs; for (Object o: unnamedArgs) { argLayouts[pos] = variadicLayout(normalize(o.getClass())); pos++; } assert pos == argsCount; FunctionDescriptor f = (function.returnLayout().isEmpty()) ? FunctionDescriptor.ofVoid(argLayouts) : FunctionDescriptor.of(function.returnLayout().get(), argLayouts); MethodHandle mh = LINKER.downcallHandle(symbol, f); boolean needsAllocator = function.returnLayout().isPresent() && function.returnLayout().get() instanceof GroupLayout; if (needsAllocator) { mh = mh.bindTo(allocator); } // flatten argument list so that it can be passed to an asSpreader MH Object[] allArgs = new Object[nNamedArgs + unnamedArgs.length]; System.arraycopy(args, 0, allArgs, 0, nNamedArgs); System.arraycopy(unnamedArgs, 0, allArgs, nNamedArgs, unnamedArgs.length); return mh.asSpreader(Object[].class, argsCount).invoke(allArgs); } private static Class<?> unboxIfNeeded(Class<?> clazz) { if (clazz == Boolean.class) { return boolean.class; } else if (clazz == Void.class) { return void.class; } else if (clazz == Byte.class) { return byte.class; } else if (clazz == Character.class) { return char.class; } else if (clazz == Short.class) { return short.class; } else if (clazz == Integer.class) { return int.class; } else if (clazz == Long.class) { return long.class; } else if (clazz == Float.class) { return float.class; } else if (clazz == Double.class) { return double.class; } else { return clazz; } } private Class<?> promote(Class<?> c) { if (c == byte.class || c == char.class || c == short.class || c == int.class) { return long.class; } else if (c == float.class) { return double.class; } else { return c; } } private Class<?> normalize(Class<?> c) { c = unboxIfNeeded(c); if (c.isPrimitive()) { return promote(c); } if (c == MemorySegment.class) { return MemorySegment.class; } throw new IllegalArgumentException("Invalid type for ABI: " + c.getTypeName()); } private MemoryLayout variadicLayout(Class<?> c) { if (c == long.class) { return JAVA_LONG; } else if (c == double.class) { return JAVA_DOUBLE; } else if (c == MemorySegment.class) { return ADDRESS; } else { throw new IllegalArgumentException("Unhandled variadic argument class: " + c); } } } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 21/P171_JextractAndModf/src/main/java/c/lib/math/constants$28.java
Chapter07/JDK 21/P171_JextractAndModf/src/main/java/c/lib/math/constants$28.java
// Generated by jextract package c.lib.math; import java.lang.invoke.MethodHandle; import java.lang.invoke.VarHandle; import java.nio.ByteOrder; import java.lang.foreign.*; import static java.lang.foreign.ValueLayout.*; final class constants$28 { // Suppresses default constructor, ensuring non-instantiability. private constants$28() {} static final MethodHandle const$0 = RuntimeHelper.downcallHandle( "tanhl", constants$10.const$2 ); static final MethodHandle const$1 = RuntimeHelper.downcallHandle( "acosh", constants$10.const$2 ); static final MethodHandle const$2 = RuntimeHelper.downcallHandle( "acoshf", constants$13.const$3 ); static final MethodHandle const$3 = RuntimeHelper.downcallHandle( "acoshl", constants$10.const$2 ); static final MethodHandle const$4 = RuntimeHelper.downcallHandle( "asinh", constants$10.const$2 ); static final MethodHandle const$5 = RuntimeHelper.downcallHandle( "asinhf", constants$13.const$3 ); }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 21/P171_JextractAndModf/src/main/java/c/lib/math/constants$34.java
Chapter07/JDK 21/P171_JextractAndModf/src/main/java/c/lib/math/constants$34.java
// Generated by jextract package c.lib.math; import java.lang.invoke.MethodHandle; import java.lang.invoke.VarHandle; import java.nio.ByteOrder; import java.lang.foreign.*; import static java.lang.foreign.ValueLayout.*; final class constants$34 { // Suppresses default constructor, ensuring non-instantiability. private constants$34() {} static final MethodHandle const$0 = RuntimeHelper.downcallHandle( "log2l", constants$10.const$2 ); static final MethodHandle const$1 = RuntimeHelper.downcallHandle( "logb", constants$10.const$2 ); static final MethodHandle const$2 = RuntimeHelper.downcallHandle( "logbf", constants$13.const$3 ); static final MethodHandle const$3 = RuntimeHelper.downcallHandle( "logbl", constants$10.const$2 ); static final MethodHandle const$4 = RuntimeHelper.downcallHandle( "modff", constants$31.const$0 ); static final MethodHandle const$5 = RuntimeHelper.downcallHandle( "modfl", constants$14.const$3 ); }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 21/P171_JextractAndModf/src/main/java/c/lib/math/constants$24.java
Chapter07/JDK 21/P171_JextractAndModf/src/main/java/c/lib/math/constants$24.java
// Generated by jextract package c.lib.math; import java.lang.invoke.MethodHandle; import java.lang.invoke.VarHandle; import java.nio.ByteOrder; import java.lang.foreign.*; import static java.lang.foreign.ValueLayout.*; final class constants$24 { // Suppresses default constructor, ensuring non-instantiability. private constants$24() {} static final MethodHandle const$0 = RuntimeHelper.downcallHandle( "__isnanf", constants$23.const$2 ); static final MethodHandle const$1 = RuntimeHelper.downcallHandle( "__isnanl", constants$20.const$1 ); static final MethodHandle const$2 = RuntimeHelper.downcallHandle( "__signbit", constants$20.const$1 ); static final MethodHandle const$3 = RuntimeHelper.downcallHandle( "__signbitf", constants$23.const$2 ); static final MethodHandle const$4 = RuntimeHelper.downcallHandle( "__signbitl", constants$20.const$1 ); static final MethodHandle const$5 = RuntimeHelper.downcallHandle( "sinf", constants$13.const$3 ); }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 21/P171_JextractAndModf/src/main/java/c/lib/math/constants$1.java
Chapter07/JDK 21/P171_JextractAndModf/src/main/java/c/lib/math/constants$1.java
// Generated by jextract package c.lib.math; import java.lang.invoke.MethodHandle; import java.lang.invoke.VarHandle; import java.nio.ByteOrder; import java.lang.foreign.*; import static java.lang.foreign.ValueLayout.*; final class constants$1 { // Suppresses default constructor, ensuring non-instantiability. private constants$1() {} static final VarHandle const$0 = constants$0.const$5.varHandle(MemoryLayout.PathElement.groupElement("wLanguage")); static final VarHandle const$1 = constants$0.const$5.varHandle(MemoryLayout.PathElement.groupElement("wCountry")); static final VarHandle const$2 = constants$0.const$5.varHandle(MemoryLayout.PathElement.groupElement("wCodePage")); static final StructLayout const$3 = MemoryLayout.structLayout( JAVA_INT.withName("refcount"), JAVA_INT.withName("lc_codepage"), JAVA_INT.withName("lc_collate_cp"), MemoryLayout.sequenceLayout(6, JAVA_INT).withName("lc_handle"), MemoryLayout.sequenceLayout(6, MemoryLayout.structLayout( JAVA_SHORT.withName("wLanguage"), JAVA_SHORT.withName("wCountry"), JAVA_SHORT.withName("wCodePage") ).withName("tagLC_ID")).withName("lc_id"), MemoryLayout.sequenceLayout(6, MemoryLayout.structLayout( RuntimeHelper.POINTER.withName("locale"), RuntimeHelper.POINTER.withName("wlocale"), RuntimeHelper.POINTER.withName("refcount"), RuntimeHelper.POINTER.withName("wrefcount") ).withName("")).withName("lc_category"), JAVA_INT.withName("lc_clike"), JAVA_INT.withName("mb_cur_max"), RuntimeHelper.POINTER.withName("lconv_intl_refcount"), RuntimeHelper.POINTER.withName("lconv_num_refcount"), RuntimeHelper.POINTER.withName("lconv_mon_refcount"), RuntimeHelper.POINTER.withName("lconv"), RuntimeHelper.POINTER.withName("ctype1_refcount"), RuntimeHelper.POINTER.withName("ctype1"), RuntimeHelper.POINTER.withName("pctype"), RuntimeHelper.POINTER.withName("pclmap"), RuntimeHelper.POINTER.withName("pcumap"), RuntimeHelper.POINTER.withName("lc_time_curr") ).withName("threadlocaleinfostruct"); static final VarHandle const$4 = constants$1.const$3.varHandle(MemoryLayout.PathElement.groupElement("refcount")); static final VarHandle const$5 = constants$1.const$3.varHandle(MemoryLayout.PathElement.groupElement("lc_codepage")); }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 21/P171_JextractAndModf/src/main/java/c/lib/math/tagLC_ID.java
Chapter07/JDK 21/P171_JextractAndModf/src/main/java/c/lib/math/tagLC_ID.java
// Generated by jextract package c.lib.math; import java.lang.invoke.MethodHandle; import java.lang.invoke.VarHandle; import java.nio.ByteOrder; import java.lang.foreign.*; import static java.lang.foreign.ValueLayout.*; /** * {@snippet : * struct tagLC_ID { * unsigned short wLanguage; * unsigned short wCountry; * unsigned short wCodePage; * }; * } */ public class tagLC_ID { public static MemoryLayout $LAYOUT() { return constants$0.const$5; } public static VarHandle wLanguage$VH() { return constants$1.const$0; } /** * Getter for field: * {@snippet : * unsigned short wLanguage; * } */ public static short wLanguage$get(MemorySegment seg) { return (short)constants$1.const$0.get(seg); } /** * Setter for field: * {@snippet : * unsigned short wLanguage; * } */ public static void wLanguage$set(MemorySegment seg, short x) { constants$1.const$0.set(seg, x); } public static short wLanguage$get(MemorySegment seg, long index) { return (short)constants$1.const$0.get(seg.asSlice(index*sizeof())); } public static void wLanguage$set(MemorySegment seg, long index, short x) { constants$1.const$0.set(seg.asSlice(index*sizeof()), x); } public static VarHandle wCountry$VH() { return constants$1.const$1; } /** * Getter for field: * {@snippet : * unsigned short wCountry; * } */ public static short wCountry$get(MemorySegment seg) { return (short)constants$1.const$1.get(seg); } /** * Setter for field: * {@snippet : * unsigned short wCountry; * } */ public static void wCountry$set(MemorySegment seg, short x) { constants$1.const$1.set(seg, x); } public static short wCountry$get(MemorySegment seg, long index) { return (short)constants$1.const$1.get(seg.asSlice(index*sizeof())); } public static void wCountry$set(MemorySegment seg, long index, short x) { constants$1.const$1.set(seg.asSlice(index*sizeof()), x); } public static VarHandle wCodePage$VH() { return constants$1.const$2; } /** * Getter for field: * {@snippet : * unsigned short wCodePage; * } */ public static short wCodePage$get(MemorySegment seg) { return (short)constants$1.const$2.get(seg); } /** * Setter for field: * {@snippet : * unsigned short wCodePage; * } */ public static void wCodePage$set(MemorySegment seg, short x) { constants$1.const$2.set(seg, x); } public static short wCodePage$get(MemorySegment seg, long index) { return (short)constants$1.const$2.get(seg.asSlice(index*sizeof())); } public static void wCodePage$set(MemorySegment seg, long index, short x) { constants$1.const$2.set(seg.asSlice(index*sizeof()), x); } public static long sizeof() { return $LAYOUT().byteSize(); } public static MemorySegment allocate(SegmentAllocator allocator) { return allocator.allocate($LAYOUT()); } public static MemorySegment allocateArray(long len, SegmentAllocator allocator) { return allocator.allocate(MemoryLayout.sequenceLayout(len, $LAYOUT())); } public static MemorySegment ofAddress(MemorySegment addr, Arena arena) { return RuntimeHelper.asArray(addr, $LAYOUT(), 1, arena); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 21/P171_JextractAndModf/src/main/java/c/lib/math/constants$35.java
Chapter07/JDK 21/P171_JextractAndModf/src/main/java/c/lib/math/constants$35.java
// Generated by jextract package c.lib.math; import java.lang.invoke.MethodHandle; import java.lang.invoke.VarHandle; import java.nio.ByteOrder; import java.lang.foreign.*; import static java.lang.foreign.ValueLayout.*; final class constants$35 { // Suppresses default constructor, ensuring non-instantiability. private constants$35() {} static final MethodHandle const$0 = RuntimeHelper.downcallHandle( "scalbn", constants$14.const$1 ); static final MethodHandle const$1 = RuntimeHelper.downcallHandle( "scalbnf", constants$32.const$0 ); static final MethodHandle const$2 = RuntimeHelper.downcallHandle( "scalbnl", constants$14.const$1 ); static final MethodHandle const$3 = RuntimeHelper.downcallHandle( "scalbln", constants$14.const$1 ); static final MethodHandle const$4 = RuntimeHelper.downcallHandle( "scalblnf", constants$32.const$0 ); static final MethodHandle const$5 = RuntimeHelper.downcallHandle( "scalblnl", constants$14.const$1 ); }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 21/P171_JextractAndModf/src/main/java/c/lib/math/constants$31.java
Chapter07/JDK 21/P171_JextractAndModf/src/main/java/c/lib/math/constants$31.java
// Generated by jextract package c.lib.math; import java.lang.invoke.MethodHandle; import java.lang.invoke.VarHandle; import java.nio.ByteOrder; import java.lang.foreign.*; import static java.lang.foreign.ValueLayout.*; final class constants$31 { // Suppresses default constructor, ensuring non-instantiability. private constants$31() {} static final FunctionDescriptor const$0 = FunctionDescriptor.of(JAVA_FLOAT, JAVA_FLOAT, RuntimeHelper.POINTER ); static final MethodHandle const$1 = RuntimeHelper.downcallHandle( "frexpf", constants$31.const$0 ); static final MethodHandle const$2 = RuntimeHelper.downcallHandle( "frexpl", constants$14.const$3 ); static final MethodHandle const$3 = RuntimeHelper.downcallHandle( "ilogb", constants$20.const$1 ); static final MethodHandle const$4 = RuntimeHelper.downcallHandle( "ilogbf", constants$23.const$2 ); static final MethodHandle const$5 = RuntimeHelper.downcallHandle( "ilogbl", constants$20.const$1 ); }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 21/P171_JextractAndModf/src/main/java/c/lib/math/constants$40.java
Chapter07/JDK 21/P171_JextractAndModf/src/main/java/c/lib/math/constants$40.java
// Generated by jextract package c.lib.math; import java.lang.invoke.MethodHandle; import java.lang.invoke.VarHandle; import java.nio.ByteOrder; import java.lang.foreign.*; import static java.lang.foreign.ValueLayout.*; final class constants$40 { // Suppresses default constructor, ensuring non-instantiability. private constants$40() {} static final MethodHandle const$0 = RuntimeHelper.downcallHandle( "ceilf", constants$13.const$3 ); static final MethodHandle const$1 = RuntimeHelper.downcallHandle( "ceill", constants$10.const$2 ); static final MethodHandle const$2 = RuntimeHelper.downcallHandle( "floorf", constants$13.const$3 ); static final MethodHandle const$3 = RuntimeHelper.downcallHandle( "floorl", constants$10.const$2 ); static final MethodHandle const$4 = RuntimeHelper.downcallHandle( "nearbyint", constants$10.const$2 ); static final MethodHandle const$5 = RuntimeHelper.downcallHandle( "nearbyintf", constants$13.const$3 ); }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 21/P171_JextractAndModf/src/main/java/c/lib/math/constants$50.java
Chapter07/JDK 21/P171_JextractAndModf/src/main/java/c/lib/math/constants$50.java
// Generated by jextract package c.lib.math; import java.lang.invoke.MethodHandle; import java.lang.invoke.VarHandle; import java.nio.ByteOrder; import java.lang.foreign.*; import static java.lang.foreign.ValueLayout.*; final class constants$50 { // Suppresses default constructor, ensuring non-instantiability. private constants$50() {} static final MethodHandle const$0 = RuntimeHelper.downcallHandle( "fminf", constants$26.const$5 ); static final MethodHandle const$1 = RuntimeHelper.downcallHandle( "fminl", constants$12.const$0 ); static final FunctionDescriptor const$2 = FunctionDescriptor.of(JAVA_DOUBLE, JAVA_DOUBLE, JAVA_DOUBLE, JAVA_DOUBLE ); static final MethodHandle const$3 = RuntimeHelper.downcallHandle( "fma", constants$50.const$2 ); static final FunctionDescriptor const$4 = FunctionDescriptor.of(JAVA_FLOAT, JAVA_FLOAT, JAVA_FLOAT, JAVA_FLOAT ); static final MethodHandle const$5 = RuntimeHelper.downcallHandle( "fmaf", constants$50.const$4 ); }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 21/P171_JextractAndModf/src/main/java/c/lib/math/constants$6.java
Chapter07/JDK 21/P171_JextractAndModf/src/main/java/c/lib/math/constants$6.java
// Generated by jextract package c.lib.math; import java.lang.invoke.MethodHandle; import java.lang.invoke.VarHandle; import java.nio.ByteOrder; import java.lang.foreign.*; import static java.lang.foreign.ValueLayout.*; final class constants$6 { // Suppresses default constructor, ensuring non-instantiability. private constants$6() {} static final StructLayout const$0 = MemoryLayout.structLayout( JAVA_INT.withName("low"), JAVA_INT.withName("high"), MemoryLayout.paddingLayout(8) ).withName(""); static final VarHandle const$1 = constants$6.const$0.varHandle(MemoryLayout.PathElement.groupElement("low")); static final VarHandle const$2 = constants$6.const$0.varHandle(MemoryLayout.PathElement.groupElement("high")); static final UnionLayout const$3 = MemoryLayout.unionLayout( RuntimeHelper.POINTER.withName("ld"), RuntimeHelper.POINTER.withName("d"), RuntimeHelper.POINTER.withName("f"), RuntimeHelper.POINTER.withName("ldt"), RuntimeHelper.POINTER.withName("dt"), RuntimeHelper.POINTER.withName("ft") ).withName("__mingw_fp_types_t"); static final VarHandle const$4 = constants$6.const$3.varHandle(MemoryLayout.PathElement.groupElement("ld")); static final VarHandle const$5 = constants$6.const$3.varHandle(MemoryLayout.PathElement.groupElement("d")); }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 21/P171_JextractAndModf/src/main/java/c/lib/math/constants$5.java
Chapter07/JDK 21/P171_JextractAndModf/src/main/java/c/lib/math/constants$5.java
// Generated by jextract package c.lib.math; import java.lang.invoke.MethodHandle; import java.lang.invoke.VarHandle; import java.nio.ByteOrder; import java.lang.foreign.*; import static java.lang.foreign.ValueLayout.*; final class constants$5 { // Suppresses default constructor, ensuring non-instantiability. private constants$5() {} static final VarHandle const$0 = constants$4.const$4.varHandle(MemoryLayout.PathElement.groupElement("high")); static final UnionLayout const$1 = MemoryLayout.unionLayout( JAVA_FLOAT.withName("x"), JAVA_INT.withName("val") ).withName("__mingw_flt_type_t"); static final VarHandle const$2 = constants$5.const$1.varHandle(MemoryLayout.PathElement.groupElement("x")); static final VarHandle const$3 = constants$5.const$1.varHandle(MemoryLayout.PathElement.groupElement("val")); static final UnionLayout const$4 = MemoryLayout.unionLayout( JAVA_DOUBLE.withName("x"), MemoryLayout.structLayout( JAVA_INT.withName("low"), JAVA_INT.withName("high"), MemoryLayout.paddingLayout(8) ).withName("lh") ).withName("__mingw_ldbl_type_t"); static final VarHandle const$5 = constants$5.const$4.varHandle(MemoryLayout.PathElement.groupElement("x")); }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 21/P171_JextractAndModf/src/main/java/c/lib/math/constants$48.java
Chapter07/JDK 21/P171_JextractAndModf/src/main/java/c/lib/math/constants$48.java
// Generated by jextract package c.lib.math; import java.lang.invoke.MethodHandle; import java.lang.invoke.VarHandle; import java.nio.ByteOrder; import java.lang.foreign.*; import static java.lang.foreign.ValueLayout.*; final class constants$48 { // Suppresses default constructor, ensuring non-instantiability. private constants$48() {} static final MethodHandle const$0 = RuntimeHelper.downcallHandle( "nextafterl", constants$12.const$0 ); static final MethodHandle const$1 = RuntimeHelper.downcallHandle( "nexttoward", constants$12.const$0 ); static final FunctionDescriptor const$2 = FunctionDescriptor.of(JAVA_FLOAT, JAVA_FLOAT, JAVA_DOUBLE ); static final MethodHandle const$3 = RuntimeHelper.downcallHandle( "nexttowardf", constants$48.const$2 ); static final MethodHandle const$4 = RuntimeHelper.downcallHandle( "nexttowardl", constants$12.const$0 ); static final MethodHandle const$5 = RuntimeHelper.downcallHandle( "fdim", constants$12.const$0 ); }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 21/P171_JextractAndModf/src/main/java/c/lib/math/constants$4.java
Chapter07/JDK 21/P171_JextractAndModf/src/main/java/c/lib/math/constants$4.java
// Generated by jextract package c.lib.math; import java.lang.invoke.MethodHandle; import java.lang.invoke.VarHandle; import java.nio.ByteOrder; import java.lang.foreign.*; import static java.lang.foreign.ValueLayout.*; final class constants$4 { // Suppresses default constructor, ensuring non-instantiability. private constants$4() {} static final VarHandle const$0 = constants$1.const$3.varHandle(MemoryLayout.PathElement.groupElement("lc_time_curr")); static final UnionLayout const$1 = MemoryLayout.unionLayout( JAVA_DOUBLE.withName("x"), JAVA_LONG.withName("val"), MemoryLayout.structLayout( JAVA_INT.withName("low"), JAVA_INT.withName("high") ).withName("lh") ).withName("__mingw_dbl_type_t"); static final VarHandle const$2 = constants$4.const$1.varHandle(MemoryLayout.PathElement.groupElement("x")); static final VarHandle const$3 = constants$4.const$1.varHandle(MemoryLayout.PathElement.groupElement("val")); static final StructLayout const$4 = MemoryLayout.structLayout( JAVA_INT.withName("low"), JAVA_INT.withName("high") ).withName(""); static final VarHandle const$5 = constants$4.const$4.varHandle(MemoryLayout.PathElement.groupElement("low")); }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter07/JDK 21/P171_JextractAndModf/src/main/java/c/lib/math/constants$32.java
Chapter07/JDK 21/P171_JextractAndModf/src/main/java/c/lib/math/constants$32.java
// Generated by jextract package c.lib.math; import java.lang.invoke.MethodHandle; import java.lang.invoke.VarHandle; import java.nio.ByteOrder; import java.lang.foreign.*; import static java.lang.foreign.ValueLayout.*; final class constants$32 { // Suppresses default constructor, ensuring non-instantiability. private constants$32() {} static final FunctionDescriptor const$0 = FunctionDescriptor.of(JAVA_FLOAT, JAVA_FLOAT, JAVA_INT ); static final MethodHandle const$1 = RuntimeHelper.downcallHandle( "ldexpf", constants$32.const$0 ); static final MethodHandle const$2 = RuntimeHelper.downcallHandle( "ldexpl", constants$14.const$1 ); static final MethodHandle const$3 = RuntimeHelper.downcallHandle( "logf", constants$13.const$3 ); static final MethodHandle const$4 = RuntimeHelper.downcallHandle( "logl", constants$10.const$2 ); static final MethodHandle const$5 = RuntimeHelper.downcallHandle( "log10f", constants$13.const$3 ); }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false