--- name: java description: Robust Java patterns — null safety with Optional, equals/hashCode contracts, Collections API, concurrent utilities, immutability, modern Java (streams, records, sealed classes, pattern matching). license: MIT --- # Java Best Practices ## Quick Reference | Topic | Section | | ------------------------------- | ---------------------------------- | | Nulls, Optional, autoboxing | `#nulls-optional-autoboxing` | | Collections and iteration | `#collections-and-iteration` | | Generics and type erasure | `#generics-and-type-erasure` | | Concurrency and synchronization | `#concurrency-and-synchronization` | | Classes, inheritance, memory | `#classes-inheritance-memory` | | Streams and CompletableFuture | `#streams-and-completablefuture` | | Testing (JUnit, Mockito) | `#testing` | | JVM, GC, modules | `#jvm-gc-modules` | --- ## Nulls, Optional, Autoboxing ### Equality: `==` vs `.equals()` - **`==` compares references**, not content - Always use `.equals()` for comparing String content ```java // Bad if (name == "admin") { ... } // Good if ("admin".equals(name)) { ... } ``` ### Optional - **`Optional.get()` throws if empty** — never use without checking - Use `orElse()`, `orElseGet()`, `orElseThrow()`, or `ifPresent()` ```java // Bad String value = optional.get(); // Good String value = optional.orElse("default"); String value = optional.orElseGet(() -> computeDefault()); optional.ifPresent(this::process); ``` ### Autoboxing Null PointerException ```java // Bad - throws NPE Integer i = null; int x = i; // NPE on unboxing // Good - check first if (i != null) { int x = i; } ``` ### Integer Caching - `Integer == Integer` uses reference comparison - Only cached for -128 to 127 - Use `.equals()` or convert to primitives ```java // Bad - may fail Integer a = 200; Integer b = 200; a == b // false, outside cache range // Good a.equals(b) // true ``` --- ## Collections and Iteration ### List Implementations - **ArrayList**: Fast random access, slow insertions/removals in middle - **LinkedList**: Fast insertions/removals, slow random access - **Default to ArrayList** unless you have specific reason ### Iteration Traps - **Modifying while iterating throws `ConcurrentModificationException`** - Use `Iterator.remove()` or collect to remove ```java // Bad for (Item item : items) { if (item.isDeleted()) { items.remove(item); // ConcurrentModificationException } } // Good Iterator it = items.iterator(); while (it.hasNext()) { if (it.next().isDeleted()) { it.remove(); } } // Or filter List filtered = items.stream() .filter(item -> !item.isDeleted()) .toList(); ``` ### Map Tips - **HashMap** — O(1) average for put/get - **LinkedHashMap** — maintains insertion order - **TreeMap** — sorted keys, O(log n) --- ## Generics and Type Erasure ### Type Erasure Generic type info is **gone at runtime**: ```java // Compile-time only - erased at runtime List strings = new ArrayList<>(); List ints = new ArrayList<>(); strings.getClass() == ints.getClass() // true! ``` ### What You CAN'T Do ```java // Can't do this T item = new T(); // No runtime type info if (obj instanceof List) { } // Can't check generic type List[] array = new List[10]; // Generic array ``` ### What You CAN Do ```java // Use bounds class Box { } class Processor { } // PECS: Producer extends, Consumer super // Use wildcards void process(List items) { } // Read items void addItems(List items) { } // Write items ``` --- ## Concurrency and Synchronization ### volatile - **`volatile` ensures visibility**, not atomicity - `count++` is NOT atomic even with volatile ```java // Bad - race condition volatile int count = 0; count++; // Not atomic! // Good - use AtomicInteger AtomicInteger count = new AtomicInteger(); count.incrementAndGet(); ``` ### Synchronized - Use `synchronized` blocks or methods - Don't hold locks across await/IO ### Concurrent Collections Prefer thread-safe collections: | Collection | Use When | | ---------------------- | ----------------------- | | `ConcurrentHashMap` | High-concurrency map | | `CopyOnWriteArrayList` | Read-heavy, rare writes | | `BlockingQueue` | Producer-consumer | | `AtomicInteger/Long` | Counters | --- ## Classes, Inheritance, Memory ### equals() and hashCode() Contract **If you override `equals()`, you MUST override `hashCode()`** ```java @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Item item = (Item) o; return Objects.equals(id, item.id); } @Override public int hashCode() { return Objects.hash(id); } ``` ### Inner Classes - Inner classes hold **implicit reference to outer class** - Can cause memory leaks if inner class outlives outer - Use **static nested class** if reference not needed ```java // Non-static - holds outer reference class Outer { class Inner { } // Can access Outer members } // Static - no outer reference class Outer { static class Inner { } // Cannot access Outer members } ``` ### serialVersionUID - **Must declare explicitly** — mismatch breaks deserialization - Generate with `serialver` tool or IDE ```java private static final long serialVersionUID = 1L; ``` --- ## Streams and CompletableFuture ### Streams Are Single-Use ```java // Bad - stream already consumed Stream stream = items.stream(); stream.forEach(System.out::println); stream.forEach(...) ``` ### thenApply vs thenCompose - **`thenApply`**: Transform result to another value - **`thenCompose`**: Chain CompletableFutures (flatten) ```java // thenApply - synchronous transformation CompletableFuture result = future.thenApply(String::toUpperCase); // thenCompose - for chaining async operations CompletableFuture user = getId() .thenCompose(this::fetchUser); // Returns CompletableFuture ``` --- ## Testing ### JUnit 5 Basics ```java import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class MyTest { @Test void testSomething() { assertEquals(4, 2 + 2); assertNotNull(object); assertTrue(condition); } @Test void testException() { assertThrows(IllegalArgumentException.class, () -> process(-1)); } } ``` ### Mockito Patterns ```java import org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) class ServiceTest { @Mock private Repository repository; @InjectMocks private Service service; @Test void testSave() { when(repository.save(any())).thenReturn(new Item(1)); Item result = service.save(new Item()); assertNotNull(result); verify(repository).save(any()); } } ``` --- ## JVM, GC, Modules ### GC Basics - **G1GC** (default since Java 9) — good for most workloads - **ZGC** — low latency, large heaps - **Shenandoah** — low pause times ### Modules (Java 9+) ```java // module-info.java module com.myapp { requires com.library; exports com.myapp.api; } ``` --- ## Related Skills - **benchmark-java**: For benchmarking Java code with JMH