<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Shahid Manzoor Meer on Medium]]></title>
        <description><![CDATA[Stories by Shahid Manzoor Meer on Medium]]></description>
        <link>https://medium.com/@meershahidmanzoor?source=rss-28fb8dc555be------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VRz7hrCgc_QjHONSyZsmzg.jpeg</url>
            <title>Stories by Shahid Manzoor Meer on Medium</title>
            <link>https://medium.com/@meershahidmanzoor?source=rss-28fb8dc555be------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 16:22:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@meershahidmanzoor/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Service Locator Factory: choosing the Right Implementation at Runtime in Spring Boot]]></title>
            <link>https://medium.com/@meershahidmanzoor/service-locator-factory-choosing-the-right-implementation-at-runtime-in-spring-boot-0cc828ae6960?source=rss-28fb8dc555be------2</link>
            <guid isPermaLink="false">https://medium.com/p/0cc828ae6960</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Shahid Manzoor Meer]]></dc:creator>
            <pubDate>Fri, 19 Dec 2025 16:10:32 GMT</pubDate>
            <atom:updated>2025-12-19T16:11:49.234Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_WRZJXTJ4asH_raqRJpqUg.png" /><figcaption>image source: <a href="https://unsplash.com/@6heinz3r?utm_source=medium&amp;utm_medium=referral">Gabriel Heinzer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>From @Autowired + if/else to Service Locator Factory</h3><h3>The Real Requirement</h3><p>In many Spring Boot applications, we face this requirement:</p><ul><li>One interface</li><li>Multiple implementations</li><li>The implementation must be chosen <strong>at runtime</strong> based on some input</li></ul><p>Example: payment processing.</p><h3>Step 1: The Common Setup (Nothing Wrong Yet)</h3><p>We start with an interface:</p><pre>public interface PaymentService {<br>    void pay(double amount);<br>}</pre><p>And multiple implementations:</p><pre>@Service<br>public class CreditCardPaymentService implements PaymentService {<br>    public void pay(double amount) {<br>        System.out.println(&quot;Paid using Credit Card&quot;);<br>    }<br>}</pre><pre>@Service<br>public class UpiPaymentService implements PaymentService {<br>    public void pay(double amount) {<br>        System.out.println(&quot;Paid using UPI&quot;);<br>    }<br>}</pre><p>So far, this is standard Spring Boot.</p><h3>Step 2: How We Usually Solve Runtime Selection</h3><p>Now we need to decide <strong>which implementation to use</strong> based on runtime input.</p><p>What most teams do is this:</p><pre>@Service<br>public class PaymentProcessor {<br><br>    private final CreditCardPaymentService creditCardPayment;<br>    private final UpiPaymentService upiPayment;<br>    @Autowired<br>    public PaymentProcessor(CreditCardPaymentService creditCardPayment,<br>                            UpiPaymentService upiPayment) {<br>        this.creditCardPayment = creditCardPayment;<br>        this.upiPayment = upiPayment;<br>    }<br><br>    public void process(String type, double amount) {<br>        if (&quot;CREDIT&quot;.equals(type)) {<br>            creditCardPayment.pay(amount);<br>        } else if (&quot;UPI&quot;.equals(type)) {<br>            upiPayment.pay(amount);<br>        }<br>    }<br>}</pre><p>This is <strong>very common</strong>.<br>And it works.</p><p>But it introduces subtle architectural problems.</p><h3>Step 3: What’s Actually Wrong With This Approach</h3><h3>1. Business Logic Knows All Implementations</h3><p>PaymentProcessor is now tightly coupled to:</p><ul><li>every concrete payment service</li><li>every supported payment type</li></ul><p>The interface abstraction is effectively bypassed.</p><h3>2. Violates Open/Closed Principle</h3><p>Add a new payment type?<br>You must:</p><ul><li>add another @Autowired</li><li>modify the if/else logic</li></ul><p>Existing code must change for new behavior.</p><h3>3. Conditional Logic Keeps Growing</h3><p>As implementations increase:</p><ul><li>if/else chains grow</li><li>logic becomes harder to read</li><li>testing becomes more complex</li></ul><p>This scales poorly.</p><h3>Step 4: Understanding the Real Problem</h3><p>The problem is <strong>not dependency injection</strong>.</p><p>The problem is <strong>manual service selection</strong>.</p><p>We are asking:</p><p><em>“Which implementation should I call?”</em></p><p>Instead of letting Spring answer that question.</p><h3>Step 5: Spring’s Intended Solution</h3><h3>Service Locator Factory</h3><p>Spring provides a built-in way to:</p><ul><li>register services</li><li>resolve them by name</li><li>choose implementations at runtime</li><li>without conditional logic</li></ul><p>This is the <strong>Service Locator Factory pattern</strong>.</p><h3>Step 6: Implementing Service Locator Factory</h3><h3>1. Name the Service Beans</h3><pre>@Service(&quot;creditPayment&quot;)<br>public class CreditCardPaymentService implements PaymentService {<br>    public void pay(double amount) {<br>        System.out.println(&quot;Paid using Credit Card&quot;);<br>    }<br>}</pre><pre>@Service(&quot;upiPayment&quot;)<br>public class UpiPaymentService implements PaymentService {<br>    public void pay(double amount) {<br>        System.out.println(&quot;Paid using UPI&quot;);<br>    }<br>}</pre><p>Bean names are now the lookup keys.</p><h3>2. Define the Locator Interface</h3><pre>public interface PaymentServiceLocator {<br>    PaymentService getService(String beanName);<br>}</pre><p>No implementation needed.</p><h3>3. Register the Locator in Configuration</h3><pre>@Configuration<br>public class ServiceLocatorConfig {<br>@Bean<br>    public FactoryBean&lt;?&gt; paymentServiceLocator() {<br>        ServiceLocatorFactoryBean factoryBean =<br>                new ServiceLocatorFactoryBean();<br>        factoryBean.setServiceLocatorInterface(PaymentServiceLocator.class);<br>        return factoryBean;<br>    }<br>}</pre><p>Spring generates the implementation automatically.</p><h3>4. Use the Locator (No Conditionals)</h3><pre>@Service<br>public class PaymentProcessor {<br>private final PaymentServiceLocator locator;<br>    public PaymentProcessor(PaymentServiceLocator locator) {<br>        this.locator = locator;<br>    }<br>    public void process(String type, double amount) {<br>        locator.getService(type).pay(amount);<br>    }<br>}</pre><h3>Step 7: Why This Is Better</h3><p>Add a new implementation:</p><pre>@Service(&quot;walletPayment&quot;)<br>public class WalletPaymentService implements PaymentService {<br>    public void pay(double amount) {<br>        System.out.println(&quot;Paid using Wallet&quot;);<br>    }<br>}</pre><p>What changes?<br>Nothing else.</p><p>No new @Autowired.<br>No new if/else.<br>No modification to existing code.</p><h3>When This Pattern Makes Sense</h3><p>Use it when:</p><ul><li>Multiple implementations exist</li><li>Selection depends on runtime data</li><li>You want to avoid conditional logic</li><li>You want clean, extensible design</li></ul><p>Do <strong>not</strong> use it when:</p><ul><li>There is only one implementation</li><li>Compile-time injection is enough</li></ul><h3>Final Thought</h3><p>If your Spring Boot service:</p><ul><li>autowires multiple implementations</li><li>uses if/else to choose one</li></ul><p>You’re doing extra work that Spring can already handle.</p><p>Service Locator Factory removes that decision logic completely.<br>Please let me know your thoughts, improvements and suggestions in the comments.</p><p>Thanks, Happy Learning</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0cc828ae6960" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java 25 is here ]]></title>
            <link>https://medium.com/@meershahidmanzoor/java-25-is-here-fd6bd2d5cd68?source=rss-28fb8dc555be------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd6bd2d5cd68</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[jdk-25]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Shahid Manzoor Meer]]></dc:creator>
            <pubDate>Fri, 10 Oct 2025 06:46:39 GMT</pubDate>
            <atom:updated>2025-10-10T07:01:17.500Z</atom:updated>
            <content:encoded><![CDATA[<p>If you have been already working with latest features of java then this post is for you to get familiar with what you need to know about java 25. It is a practical guide which demonstrates what you have been doing in earlier features of java and how it has been improved in java 25.(Skipping the things which we do not need at the moment and which we do not use on daily basis). I have tried to set the base for the complex concepts like concurrency using easy to understand description and examples.</p><p>Let’s keep this guide aligned with:</p><ul><li>what we used to do (with small snippets),</li><li>what Java 25 introduces, why it’s nicer,</li><li>and matching example code.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wDpyieeTy33wGpvI5GAIMg.png" /><figcaption>Image source: stackOverFlow</figcaption></figure><h3><strong>Parallel I/O</strong></h3><p>When a request needs <strong>multiple I/O calls</strong> (DB + HTTP, or two services), doing them <strong>in parallel</strong> lowers latency. The question is: <em>how do we start, wait, fail fast, and cancel the rest safely?</em></p><h4><strong>Before — </strong><strong>CompletableFuture with manual cancel/timeout</strong></h4><p><strong>What we did:</strong></p><p>We fired off several CompletableFutures, raced or joined them, and then <strong>manually</strong> handled timeouts and cancellations.</p><p>Pain points (why this was hard)</p><p><strong>Lifecycle orchestration by hand</strong>: you must cancel “losing” tasks yourself.</p><p><strong>Easy to leak work</strong>: one failure doesn’t automatically stop siblings.</p><p><strong>Scattered error handling</strong>: cancellations/timeouts spread across futures and try/finally blocks.</p><p><strong>Minimal example (old way)</strong></p><pre>import java.net.http.*;<br>import java.net.URI;<br>import java.util.concurrent.*;<br><br>public class FetchAny {<br>  static HttpClient http = HttpClient.newHttpClient();<br><br>  static CompletableFuture&lt;String&gt; fetch(String url) {<br>    return http.sendAsync(HttpRequest.newBuilder(URI.create(url)).build(),<br>                          HttpResponse.BodyHandlers.ofString())<br>               .orTimeout(2, TimeUnit.SECONDS)        // per-task timeout<br>               .thenApply(HttpResponse::body);<br>  }<br><br>  public static void main(String[] args) {<br>    var a = fetch(&quot;https://example.com/a&quot;);<br>    var b = fetch(&quot;https://example.com/b&quot;);<br><br>    String body = (String) CompletableFuture.anyOf(a, b).join();<br><br>    // you must cancel the loser(s), or they keep running:<br>    a.cancel(true);<br>    b.cancel(true);<br><br>    System.out.println(body.substring(0, Math.min(60, body.length())));<br>  }<br>}</pre><h4><strong>Java 25 — Structured Concurrency (</strong><strong>StructuredTaskScope) <em>(preview)</em></strong></h4><p><strong>What changes:</strong></p><p>Java 25 adds a <strong>structured concurrency</strong> API that treats a set of related subtasks as <strong>one unit</strong>. Open a scope, fork subtasks, join() once, and the runtime <strong>cancels siblings automatically</strong> when policy conditions are met (e.g., one fails, or the <em>first success wins</em>). This API is <strong>preview</strong>—enable it with --enable-preview.</p><p><strong>Key updates in the JDK 25 preview:</strong></p><ul><li>StructuredTaskScope lives in <strong>java.util.concurrent</strong>.</li><li>You <strong>open</strong> a scope via StructuredTaskScope.open(...) (not by new).</li><li><strong>Joiners</strong> express your policy (all succeed, any success, etc.).</li></ul><h4>Why it’s nicer (benefits)</h4><ul><li><strong>Fail-fast &amp; auto-cancel</strong>: if one subtask fails (or a policy is met), the scope cancels the rest.</li><li><strong>One place to wait &amp; handle errors</strong>: join() centralizes completion and exceptions. <a href="https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/concurrent/StructuredTaskScope.html">Oracle Docs</a></li><li><strong>Observability &amp; clarity</strong>: subtasks live and die <strong>inside</strong> the scope block — no stray threads.</li><li><strong>Virtual-thread friendly</strong>: the default uses virtual threads for cheap, massive concurrency.</li></ul><h4>Minimal example (new way: “first success wins”)</h4><pre>import java.net.http.*;<br>import java.net.URI;<br>import java.util.concurrent.*;<br>import java.util.concurrent.StructuredTaskScope; // preview API<br><br>public class FetchAnyScoped {<br>  static HttpClient http = HttpClient.newHttpClient();<br><br>  static String fetch(String url) throws Exception {<br>    var res = http.send(HttpRequest.newBuilder(URI.create(url)).build(),<br>                        HttpResponse.BodyHandlers.ofString());<br>    return res.body();<br>  }<br><br>  public static void main(String[] args) throws Exception {<br>    // Joiner.anySuccessfulResultOrThrow(): return first successful result,<br>    // cancel the rest; if all fail, throw.<br>    try (var scope = StructuredTaskScope.open(<br>            StructuredTaskScope.Joiner.&lt;String&gt;anySuccessfulResultOrThrow())) {<br><br>      scope.fork(() -&gt; fetch(&quot;https://example.com/a&quot;));<br>      scope.fork(() -&gt; fetch(&quot;https://example.com/b&quot;));<br><br>      String body = scope.join();   // returns the winner, cancels others<br>      System.out.println(body.substring(0, Math.min(60, body.length())));<br>    }<br>  }<br>}</pre><h3>Request context</h3><p>During one request, many layers (controller → service → repository → helpers) all need the same “ambient” info like requestId or userId for logging, tracing, and auth checks.<br> If you <strong>pass it as a parameter everywhere</strong>, your method signatures get noisy, it’s easy to forget to pass it to a helper, and logs go missing or inconsistent.</p><h4><strong>How </strong><strong>ThreadLocal solved it (idea) ?</strong></h4><p>In classic Java servers (one worker thread per request), ThreadLocal gives each thread its <strong>own private storage</strong> (a little per-thread map).<br> You put the context into that storage at the start of the request, then <strong>any code running on that same thread</strong> can read it—no need to pass it as a parameter. When you finish, you <strong>remove</strong> it so the next request on that thread doesn’t see stale data.</p><p>Example with old method using <strong>ThreadLocal</strong></p><pre>// ThreadLocalDemo.java<br>class ThreadLocalDemo {<br>  static class Context {<br>    static final ThreadLocal&lt;String&gt; REQUEST_ID = new ThreadLocal&lt;&gt;();<br>  }<br><br>  static class Logger {<br>    static void log(String msg) {<br>      System.out.println(&quot;[&quot; + Context.REQUEST_ID.get() + &quot;] &quot; + msg);<br>    }<br>  }<br><br>  static class Repo {<br>    static void saveUser(String user) {<br>      Logger.log(&quot;Repo.saveUser(&quot; + user + &quot;)&quot;);<br>    }<br>  }<br><br>  static class Service {<br>    static void register(String user) {<br>      Logger.log(&quot;Service.register start&quot;);<br>      Repo.saveUser(user);<br>      helper(); // ✅ no parameter needed; still logs with requestId<br>      Logger.log(&quot;Service.register end&quot;);<br>    }<br><br>    static void helper() {<br>      Logger.log(&quot;helper doing work&quot;);<br>    }<br>  }<br><br>  public static void main(String[] args) {<br>    handleRequest(&quot;req-123&quot;, () -&gt; Service.register(&quot;alice&quot;));<br>    handleRequest(&quot;req-456&quot;, () -&gt; Service.register(&quot;bob&quot;));<br>  }<br><br>  // Bind/unbind per request on the SAME thread<br>  static void handleRequest(String requestId, Runnable work) {<br>    try {<br>      Context.REQUEST_ID.set(requestId);  // put value in this thread&#39;s drawer<br>      work.run();<br>    } finally {<br>      Context.REQUEST_ID.remove();        // IMPORTANT: prevent leaks on pools<br>    }<br>  }<br>}</pre><h4>Why this worked so well for years</h4><ul><li>Typical servers used <strong>one thread per request</strong>. The context stayed on that thread for the entire request.</li><li>You avoided parameter bloat and still got consistent logs/tracing deep in the stack.</li></ul><h4>Important caution (even with ThreadLocal)</h4><ul><li>Always remove() in a finally block. In thread pools, the same thread handles the next request; forgetting remove() leaks context to the next request.</li><li>ThreadLocal is <strong>per-thread</strong>, not per-task: if you hop to another thread (async/futures), the context doesn’t come along unless you capture/restore it yourself.</li></ul><h4>What Java 25 added</h4><p><strong>java.lang.ScopedValue&lt;T&gt;</strong> lets you bind a value for the <strong>dynamic scope</strong> of a block via ScopedValue.where(key, value).run(...) or .call(...).<br> Key properties vs ThreadLocal:</p><ul><li><strong>Bounded lifetime:</strong> binding exists only during run/call, then auto-unbinds. No manual remove().</li><li><strong>Immutable by design:</strong> there’s no set() after binding; callees can only read, not change.</li><li><strong>Per-thread binding with safe inheritance to child tasks</strong> (e.g., with structured concurrency), so the same context can be read in forks and then guaranteed to end before the binding closes. <em>(Structured Concurrency is still preview in JDK 25.)</em></li></ul><h4>Working example using <strong>java.lang.ScopedValue&lt;T&gt;</strong></h4><pre>import java.lang.ScopedValue;<br>import static java.lang.ScopedValue.where;<br><br>public class ScopedValueDemo {<br>  static final ScopedValue&lt;String&gt; REQ_ID = ScopedValue.newInstance();<br><br>  static void controller(String rid) {<br>    // Bind REQ_ID only for this call tree<br>    where(REQ_ID, rid).run(() -&gt; {<br>      service();<br>    }); // &lt;- unbound automatically here<br>  }<br><br>  static void service() {<br>    repo();<br>    log(&quot;done&quot;);<br>  }<br><br>  static void repo() {<br>    log(&quot;saving to DB&quot;);<br>  }<br><br>  static void log(String msg) {<br>    // Safe to read only inside the binding<br>    System.out.println(&quot;[&quot; + REQ_ID.get() + &quot;] &quot; + msg);<br>  }<br><br>  public static void main(String[] args) {<br>    controller(&quot;req-123&quot;);         // prints [req-123] ...<br>    try { REQ_ID.get(); } catch (Exception e) {<br>      System.out.println(&quot;Outside binding: &quot; + e); // shows it&#39;s unbound now<br>    }<br>  }<br>}</pre><p>conclusion: it directly addresses the inherent problems of ThreadLocal—<strong>unconstrained mutability, unbounded lifetime/leaks, and expensive inheritance</strong>—called out in the JEP.</p><h3>Switch / checks</h3><h4>Before — casts &amp; wrapper types only</h4><p>Historically you couldn’t switch on every primitive (e.g., no boolean, long), and safe “narrowing” checks (like “does int fit in byte?”) meant hand-rolled range guards or wrapper patterns.</p><pre>// Old: manual checks and wrapper-only patterns<br>static String classify(Object x) {<br>  if (x instanceof Integer i) return &quot;int: &quot; + i;       // wrapper<br>  if (x instanceof Long    l) return &quot;long: &quot; + l;<br>  if (x instanceof Double  d) return &quot;double: &quot; + d;<br>  if (x instanceof String  s) return &quot;string: &quot; + s;<br>  return &quot;other&quot;;<br>}<br><br>static String fitsInByte(int v) {<br>  if (v &gt;= -128 &amp;&amp; v &lt;= 127) return &quot;fits: &quot; + (byte) v; // manual check<br>  return &quot;too big&quot;;<br>}</pre><h4>Java 25 — <strong>Primitive patterns</strong> in instanceof &amp; switch (<strong>preview</strong>)</h4><p>Java 25 previews “primitive type patterns” so you can pattern-match over <strong>all primitives</strong>, use instanceof to <strong>safely check narrowing</strong>, and switch on boolean, long, etc.</p><p><strong>Example</strong></p><pre>// Compile &amp; run preview code with:<br>// javac --release 25 --enable-preview P.java<br>// java  --enable-preview P<br>class P {<br>  static String safeNarrow(int v) {<br>    if (v instanceof byte b) return &quot;fits in byte: &quot; + b; // exact conversion only<br>    return &quot;too big&quot;;<br>  }<br><br>  static String boolSwitch(boolean b) {<br>    return switch (b) { case true -&gt; &quot;yep&quot;; case false -&gt; &quot;nope&quot;; };<br>  }<br><br>  static String longSwitch(long v) {<br>    return switch (v) {<br>      case 1L -&gt; &quot;one&quot;;<br>      case 10_000_000_000L -&gt; &quot;ten billion&quot;;<br>      case long x -&gt; &quot;other: &quot; + x; // primitive pattern<br>    };<br>  }<br><br>  public static void main(String[] args) {<br>    System.out.println(safeNarrow(120));<br>    System.out.println(boolSwitch(false));<br>    System.out.println(longSwitch(10_000_000_000L));<br>  }<br>}</pre><h3>Constructors</h3><h4><strong>Before — validations after </strong><strong>super(...)</strong></h4><p>You had to call super(...) first; only then could you validate or compute arguments, so you might do work before discovering bad inputs.</p><p><strong>Example</strong></p><pre>class Person { final int age; Person(int age){ this.age = age; } }<br>class Employee extends Person {<br>  Employee(int age) {<br>    super(age);                              // must be first (old rule)<br>    if (age &lt; 18 || age &gt; 67) throw new IllegalArgumentException();<br>  }<br>}</pre><h4><strong>Java 25 — Flexible constructor bodies (final)</strong></h4><p>You can execute a <strong>prologue</strong> of statements <strong>before</strong> the explicit constructor invocation, as long as you don’t use the not-yet-constructed this. Great for validation and preparing args.</p><p><strong>Example</strong></p><pre>class Person { final int age; Person(int age){ this.age = age; } }<br>class Employee extends Person {<br>  Employee(int age) {<br>    if (age &lt; 18 || age &gt; 67) throw new IllegalArgumentException(); // prologue<br>    super(age);                                                     // then call<br>    // epilogue...<br>  }<br>}</pre><p><strong>Why nicer</strong></p><ul><li>Fail fast <strong>before</strong> any superclass work.</li><li>Expressive, safer initialization paths</li></ul><h3>Toy apps / scripts</h3><h4>Before — boilerplate class + public static void main(String[] args)</h4><p><strong>Example</strong></p><pre>public class Hello {<br>  public static void main(String[] args) {<br>    System.out.println(&quot;Hello&quot;);<br>  }<br>}</pre><h4>Java 25 — <strong>Compact source files</strong> + <strong>instance </strong><strong>main</strong> + <strong>IO.println</strong> (final)</h4><p><strong>Example</strong></p><pre>// Hello.java (compact source file)<br>void main() {<br>  IO.println(&quot;Hello, World!&quot;);<br>}</pre><p><strong>Why nicer</strong></p><ul><li>Minimal ceremony for learning/scripts.</li><li>Still evolves cleanly into a normal class later.</li></ul><h3>Imports (learning)</h3><h4>Before — many package imports</h4><p><strong>Example</strong></p><pre>import java.util.*;<br>import java.time.*;</pre><h4>Java 25 — <strong>import module …;</strong> (final)</h4><p>You can import <strong>all exported packages of a module</strong> in one shot (e.g., java.sql). Handy for teaching and quick snippets (use with care in large codebases due to name clashes).</p><p><strong>Example</strong></p><pre>// In a normal source file (best inside a named module)<br>import module java.sql;     // brings java.sql.* &amp; its indirect exports into scope<br><br>class Demo {<br>  void main() {<br>    var list = java.util.List.of(1,2,3); // still fine to use FQNs explicitly<br>  }<br>}</pre><h3>PEM files</h3><h4>Before — manual parsing or 3rd-party libs</h4><p>Developers hand-parsed -----BEGIN …----- blobs or pulled in libraries just to encode/decode keys &amp; certs.</p><p><strong>Example</strong>:</p><pre>// ManualPemDemo.java<br>import java.io.ByteArrayInputStream;<br>import java.nio.charset.StandardCharsets;<br>import java.security.KeyFactory;<br>import java.security.PrivateKey;<br>import java.security.spec.PKCS8EncodedKeySpec;<br>import java.security.cert.CertificateFactory;<br>import java.security.cert.X509Certificate;<br>import java.util.Base64;<br><br>public class ManualPemDemo {<br><br>  // --- demo PEM strings (PKCS#8 private key, X.509 certificate) ---<br>  static final String PRIVATE_KEY_PEM = &quot;&quot;&quot;<br>    -----BEGIN PRIVATE KEY-----<br>    MIIEv...<br>    ...snip...<br>    ...Q==<br>    -----END PRIVATE KEY-----<br>    &quot;&quot;&quot;;<br><br>  static final String CERT_PEM = &quot;&quot;&quot;<br>    -----BEGIN CERTIFICATE-----<br>    MIIC+D...<br>    ...snip...<br>    ...w==<br>    -----END CERTIFICATE-----<br>    &quot;&quot;&quot;;<br><br>  public static void main(String[] args) throws Exception {<br>    // Private key (PKCS#8). Change algorithm &quot;RSA&quot; -&gt; &quot;EC&quot; if your key is EC.<br>    byte[] pkcs8 = decodePem(PRIVATE_KEY_PEM, &quot;PRIVATE KEY&quot;);<br>    PrivateKey privateKey = KeyFactory.getInstance(&quot;RSA&quot;)<br>        .generatePrivate(new PKCS8EncodedKeySpec(pkcs8));<br>    System.out.println(&quot;Loaded private key: &quot; + privateKey.getAlgorithm());<br><br>    // Certificate (X.509)<br>    byte[] x509 = decodePem(CERT_PEM, &quot;CERTIFICATE&quot;);<br>    X509Certificate cert = (X509Certificate) CertificateFactory.getInstance(&quot;X.509&quot;)<br>        .generateCertificate(new ByteArrayInputStream(x509));<br>    System.out.println(&quot;Loaded certificate: &quot; + cert.getSubjectX500Principal());<br><br>    // (Optional) encode DER bytes back to PEM (very basic)<br>    String pemAgain = toPem(&quot;CERTIFICATE&quot;, x509);<br>    System.out.println(pemAgain.split(&quot;\n&quot;)[0]); // prints &quot;-----BEGIN CERTIFICATE-----&quot;<br>  }<br><br>  // Extracts and Base64-decodes the body between BEGIN/END lines.<br>  static byte[] decodePem(String pem, String type) {<br>    String begin = &quot;-----BEGIN &quot; + type + &quot;-----&quot;;<br>    String end   = &quot;-----END &quot; + type + &quot;-----&quot;;<br>    String body = pem.replace(begin, &quot;&quot;)<br>                     .replace(end, &quot;&quot;)<br>                     .replaceAll(&quot;\\s&quot;, &quot;&quot;); // strip all whitespace/newlines<br>    return Base64.getDecoder().decode(body);<br>  }<br><br>  // Minimal PEM encoder (wrap at 64 chars).<br>  static String toPem(String type, byte[] der) {<br>    String b64 = Base64.getEncoder().encodeToString(der);<br>    StringBuilder sb = new StringBuilder()<br>        .append(&quot;-----BEGIN &quot;).append(type).append(&quot;-----\n&quot;);<br>    for (int i = 0; i &lt; b64.length(); i += 64) {<br>      sb.append(b64, i, Math.min(i + 64, b64.length())).append(&#39;\n&#39;);<br>    }<br>    sb.append(&quot;-----END &quot;).append(type).append(&quot;-----\n&quot;);<br>    return sb.toString();<br>  }<br>}</pre><h4>Java 25 — PEM encodings API (preview)</h4><p>First-class java.security API: PEMEncoder, PEMDecoder, and PEMRecord handle keys, certs, and CRLs. Enable with --enable-preview.</p><p><strong>Example</strong></p><pre>// PemDemo.java  (preview)<br>// javac --release 25 --enable-preview PemDemo.java<br>// java  --enable-preview PemDemo<br>import java.security.*;<br>import java.security.PEMEncoder;  // preview API<br>import java.security.PEMDecoder;  // preview API<br>import java.security.cert.X509Certificate;<br><br>public class PemDemo {<br>  public static void main(String[] args) throws Exception {<br>    var kpg = KeyPairGenerator.getInstance(&quot;EC&quot;);<br>    kpg.initialize(256);<br>    var kp = kpg.generateKeyPair();<br><br>    // Encode private key to PEM text<br>    String pemPriv = PEMEncoder.of().encodeToString(kp.getPrivate());<br>    System.out.println(pemPriv.split(&quot;\n&quot;)[0]); // ----BEGIN PRIVATE KEY----<br><br>    // Decode back to a PrivateKey<br>    PrivateKey pk = PEMDecoder.of().decode(pemPriv, PrivateKey.class);<br>    System.out.println(&quot;Decoded: &quot; + pk.getAlgorithm());<br>  }<br>}</pre><p><strong>Why nicer</strong></p><ul><li>No brittle string parsing; one small standard API for encode/decode.</li><li>Works for keys, certs, and CRLs; supports provider selection</li></ul><p>If you are here and you really enjoyed this post do like, comment your thoughts or additional information , share it with your friends. I have tried my best to keep it as simple as that. <br>Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd6bd2d5cd68" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>