|
| 1 | +# Spacecraft Java Guidelines — Full Reference |
| 2 | + |
| 3 | +**Version:** 1.0 |
| 4 | +**Date:** 2026-07-13 |
| 5 | +**Author:** Mohamed Hammad & Spacecraft Software |
| 6 | +**Compatibility:** JDK 21+, OpenJDK 21+, Generational ZGC |
| 7 | + |
| 8 | +This document expands on the `SKILL.md` for Java systems programming. It provides complete, compile-checked configurations and skeletons for Virtual Threads, Structured Concurrency, resource management, and unit testing. |
| 9 | + |
| 10 | +--- |
| 11 | + |
| 12 | +## 1. Virtual Threads (Project Loom) Executor Flow |
| 13 | + |
| 14 | +Virtual threads are lightweight, user-mode threads scheduled by the JVM on carrier platform threads. Never pool virtual threads. Create them on-demand per task. |
| 15 | + |
| 16 | +```java |
| 17 | +package org.spacecraftsoftware.telemetry; |
| 18 | + |
| 19 | +import java.util.List; |
| 20 | +import java.util.concurrent.Callable; |
| 21 | +import java.util.concurrent.ExecutionException; |
| 22 | +import java.util.concurrent.Executors; |
| 23 | +import java.util.concurrent.Future; |
| 24 | + |
| 25 | +public class VirtualThreadProcessor { |
| 26 | + |
| 27 | + public record TelemetryTask(String sensorId) implements Callable<Double> { |
| 28 | + @Override |
| 29 | + public Double call() throws Exception { |
| 30 | + // Simulate blocking I/O network poll |
| 31 | + Thread.sleep(50); |
| 32 | + return Math.random() * 100.0; |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + public List<Double> fetchAllTelemetry(List<String> sensorIds) throws InterruptedException { |
| 37 | + // CRITICAL: Banish thread pools for virtual threads. Spawn on-demand. |
| 38 | + // Use try-with-resources to automatically close the executor (which awaits task completion). |
| 39 | + try (var executor = Executors.newVirtualThreadPerTaskExecutor()) { |
| 40 | + List<TelemetryTask> tasks = sensorIds.stream() |
| 41 | + .map(TelemetryTask::new) |
| 42 | + .toList(); |
| 43 | + |
| 44 | + List<Future<Double>> futures = executor.invokeAll(tasks); |
| 45 | + |
| 46 | + return futures.stream() |
| 47 | + .map(f -> { |
| 48 | + try { |
| 49 | + return f.get(); |
| 50 | + } catch (InterruptedException | ExecutionException e) { |
| 51 | + Thread.currentThread().interrupt(); |
| 52 | + throw new RuntimeException("Telemetry fetch failed", e); |
| 53 | + } |
| 54 | + }) |
| 55 | + .toList(); |
| 56 | + } |
| 57 | + } |
| 58 | +} |
| 59 | +``` |
| 60 | + |
| 61 | +--- |
| 62 | + |
| 63 | +## 2. Preventing Virtual Thread Pinning with ReentrantLock |
| 64 | + |
| 65 | +Avoid using `synchronized` blocks or methods when executing blocking I/O inside virtual threads. If a virtual thread blocks inside `synchronized`, it pins its carrier platform thread, causing carrier thread starvation. Replace `synchronized` with `ReentrantLock`. |
| 66 | + |
| 67 | +```java |
| 68 | +package org.spacecraftsoftware.telemetry; |
| 69 | + |
| 70 | +import java.util.ArrayList; |
| 71 | +import java.util.List; |
| 72 | +import java.util.concurrent.locks.ReentrantLock; |
| 73 | + |
| 74 | +public class PinFreeTelemetryLogger { |
| 75 | + |
| 76 | + private final ReentrantLock lock = new ReentrantLock(); |
| 77 | + private final List<String> logs = new ArrayList<>(); |
| 78 | + |
| 79 | + public void logEvent(String event) { |
| 80 | + // CRITICAL: Replace synchronized(this) { ... } with explicit ReentrantLock |
| 81 | + // to prevent pinning the carrier thread during downstream blocking calls. |
| 82 | + lock.lock(); |
| 83 | + try { |
| 84 | + logs.add(event); |
| 85 | + // Simulate blocking write (disk write / network flush) |
| 86 | + writeToDisk(event); |
| 87 | + } finally { |
| 88 | + lock.unlock(); // Always release inside finally block |
| 89 | + } |
| 90 | + } |
| 91 | + |
| 92 | + private void writeToDisk(String data) { |
| 93 | + try { |
| 94 | + // Simulate blocking disk I/O |
| 95 | + Thread.sleep(10); |
| 96 | + } catch (InterruptedException e) { |
| 97 | + Thread.currentThread().interrupt(); |
| 98 | + } |
| 99 | + } |
| 100 | + |
| 101 | + public List<String> getLogs() { |
| 102 | + lock.lock(); |
| 103 | + try { |
| 104 | + return List.copyOf(logs); |
| 105 | + } finally { |
| 106 | + lock.unlock(); |
| 107 | + } |
| 108 | + } |
| 109 | +} |
| 110 | +``` |
| 111 | + |
| 112 | +--- |
| 113 | + |
| 114 | +## 3. Structured Concurrency (JEP 462+) |
| 115 | + |
| 116 | +Structured Concurrency treats groups of concurrent tasks as a single unit of work, improving reliability and cancellation tracking. |
| 117 | + |
| 118 | +```java |
| 119 | +package org.spacecraftsoftware.telemetry; |
| 120 | + |
| 121 | +import java.util.concurrent.StructuredTaskScope; |
| 122 | +import java.util.concurrent.StructuredTaskScope.Subtask; |
| 123 | +import java.time.Instant; |
| 124 | + |
| 125 | +public class ResilientTaskScheduler { |
| 126 | + |
| 127 | + public record ServiceResponse(String data, Instant timestamp) {} |
| 128 | + |
| 129 | + public ServiceResponse queryResilientData() throws Exception { |
| 130 | + // Use StructuredTaskScope to coordinate subtasks. ShutdownOnFailure shuts down |
| 131 | + // all subtasks immediately if any single subtask fails (fail-fast behavior). |
| 132 | + try (var scope = new StructuredTaskScope.ShutdownOnFailure()) { |
| 133 | + |
| 134 | + // Fork subtask queries |
| 135 | + Subtask<String> dbSubtask = scope.fork(() -> queryDatabase()); |
| 136 | + Subtask<Instant> timeSubtask = scope.fork(() -> fetchNetworkTime()); |
| 137 | + |
| 138 | + scope.join(); // Join both subtasks |
| 139 | + scope.throwIfFailed(); // Propagate exceptions if any subtask failed |
| 140 | + |
| 141 | + // Safe retrieval of results |
| 142 | + return new ServiceResponse(dbSubtask.get(), timeSubtask.get()); |
| 143 | + } |
| 144 | + } |
| 145 | + |
| 146 | + private String queryDatabase() throws Exception { |
| 147 | + Thread.sleep(30); |
| 148 | + return "Spacecraft Coordinates Active"; |
| 149 | + } |
| 150 | + |
| 151 | + private Instant fetchNetworkTime() throws Exception { |
| 152 | + Thread.sleep(20); |
| 153 | + return Instant.now(); |
| 154 | + } |
| 155 | +} |
| 156 | +``` |
| 157 | + |
| 158 | +--- |
| 159 | + |
| 160 | +## 4. Resource Safety: try-with-resources |
| 161 | + |
| 162 | +Always wrap resource declarations implementing `AutoCloseable` in `try-with-resources` statements to prevent heap memory leak traps. |
| 163 | + |
| 164 | +```java |
| 165 | +package org.spacecraftsoftware.telemetry; |
| 166 | + |
| 167 | +import java.io.BufferedReader; |
| 168 | +import java.io.FileReader; |
| 169 | +import java.io.IOException; |
| 170 | +import java.nio.file.Path; |
| 171 | + |
| 172 | +public class TelemetryFileReader { |
| 173 | + |
| 174 | + public String readFirstTelemetryLine(Path filePath) throws IOException { |
| 175 | + // CRITICAL: Banish resource leaks by ensuring try-with-resources handles autoclosing |
| 176 | + try (var fileReader = new FileReader(filePath.toFile()); |
| 177 | + var bufferedReader = new BufferedReader(fileReader)) { |
| 178 | + |
| 179 | + String line = bufferedReader.readLine(); |
| 180 | + return line != null ? line : ""; |
| 181 | + } |
| 182 | + } |
| 183 | +} |
| 184 | +``` |
| 185 | + |
| 186 | +--- |
| 187 | + |
| 188 | +## 5. Sequenced Collections and Record Constants |
| 189 | + |
| 190 | +Java 21 introduces Sequenced Collections, standardizing collection retrieval order. Combine with record classes for clean, type-safe data access. |
| 191 | + |
| 192 | +```java |
| 193 | +package org.spacecraftsoftware.telemetry; |
| 194 | + |
| 195 | +import java.util.LinkedHashSet; |
| 196 | +import java.util.SequencedSet; |
| 197 | + |
| 198 | +public class SequenceManager { |
| 199 | + |
| 200 | + public record SensorReading(int sensorId, double value) {} |
| 201 | + |
| 202 | + public void processSequencedReadings() { |
| 203 | + SequencedSet<SensorReading> readings = new LinkedHashSet<>(); |
| 204 | + readings.add(new SensorReading(1, 12.3)); |
| 205 | + readings.add(new SensorReading(2, 45.6)); |
| 206 | + readings.add(new SensorReading(3, 78.9)); |
| 207 | + |
| 208 | + // Retrieve first and last elements cleanly |
| 209 | + SensorReading first = readings.getFirst(); |
| 210 | + SensorReading last = readings.getLast(); |
| 211 | + |
| 212 | + System.out.println("First reading: " + first.value()); |
| 213 | + System.out.println("Last reading: " + last.value()); |
| 214 | + |
| 215 | + // Traverse in reverse order |
| 216 | + for (SensorReading r : readings.reversed()) { |
| 217 | + System.out.println("Reversed: " + r.sensorId()); |
| 218 | + } |
| 219 | + } |
| 220 | +} |
| 221 | +``` |
| 222 | + |
| 223 | +--- |
| 224 | + |
| 225 | +## 6. Testing: JUnit 5 Integration |
| 226 | + |
| 227 | +Write structured test validations using JUnit 5 assertions. |
| 228 | + |
| 229 | +```java |
| 230 | +package org.spacecraftsoftware.telemetry; |
| 231 | + |
| 232 | +import org.junit.jupiter.api.Test; |
| 233 | +import java.io.IOException; |
| 234 | +import java.nio.file.Files; |
| 235 | +import java.nio.file.Path; |
| 236 | +import java.util.List; |
| 237 | + |
| 238 | +import static org.junit.jupiter.api.Assertions.*; |
| 239 | + |
| 240 | +class TelemetryWorkerTest { |
| 241 | + |
| 242 | + @Test |
| 243 | + void testVirtualThreadExecution() throws Exception { |
| 244 | + VirtualThreadProcessor processor = new VirtualThreadProcessor(); |
| 245 | + List<String> sensors = List.of("GPS_01", "GYRO_02", "TEMP_03"); |
| 246 | + |
| 247 | + List<Double> results = processor.fetchAllTelemetry(sensors); |
| 248 | + |
| 249 | + assertNotNull(results); |
| 250 | + assertEquals(3, results.size()); |
| 251 | + for (Double reading : results) { |
| 252 | + assertTrue(reading >= 0.0 && reading <= 100.0); |
| 253 | + } |
| 254 | + } |
| 255 | + |
| 256 | + @Test |
| 257 | + void testTelemetryFileReaderLeaks() throws IOException { |
| 258 | + Path tempFile = Files.createTempFile("telemetry_mock", ".log"); |
| 259 | + Files.writeString(tempFile, "SYSTEM_OK\nDETAILS_MOCK"); |
| 260 | + |
| 261 | + TelemetryFileReader reader = new TelemetryFileReader(); |
| 262 | + String result = reader.readFirstTelemetryLine(tempFile); |
| 263 | + |
| 264 | + assertEquals("SYSTEM_OK", result); |
| 265 | + Files.delete(tempFile); |
| 266 | + } |
| 267 | +} |
| 268 | +``` |
0 commit comments