⚡ AutoSnippets PRO PL

Java: Production Code Snippets

Production Java patterns: multithreading, HTTP, file handling, servlet middleware.

Python JavaScript TypeScript Java C# C++ Go PHP Rust SQL

On this page:

16. Java: Thread-Safe Singleton (DCL)

Java

Lazy initialization with double-checked locking in a multithreaded environment.

public class SecureSingleton {
    private static volatile SecureSingleton instance;
    private SecureSingleton() {}
    
    public static SecureSingleton getInstance() {
        if (instance == null) {
            synchronized (SecureSingleton.class) {
                if (instance == null) {
                    instance = new SecureSingleton();
                }
            }
        }
        return instance;
    }
}

When to use

Use it when you need exactly one shared instance of an object across threads (e.g. a connection pool, configuration).

Common pitfalls

Double-checked locking requires the volatile keyword on the instance field — without it you can get a partially initialized object.

17. Java: Thread Pool and ExecutorService

Java

Async processing of task batches using Future objects.

import java.util.concurrent.*;

public class TaskProcessor {
    public static void run() {
        ExecutorService executor = Executors.newFixedThreadPool(4);
        Future future = executor.submit(() -> {
            Thread.sleep(1000);
            return "Wynik zadania w tle";
        });
        executor.shutdown();
    }
}

When to use

Use it instead of manually creating threads (`new Thread()`) when processing many background tasks — resources are easier to control.

Common pitfalls

Not calling executor.shutdown() keeps the application running, since the pool's threads remain active.

18. Java: Modern HttpClient

Java

An advanced network request using Java's native API.

import java.net.URI;
import java.net.http.*;

public class ApiClient {
    public static String get(String url) throws Exception {
        HttpClient client = HttpClient.newBuilder().build();
        HttpRequest request = HttpRequest.newBuilder().uri(URI.create(url)).build();
        HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString());
        return response.body();
    }
}

When to use

Recommended over the older HttpURLConnection for talking to external APIs in modern Java 11+ applications.

Common pitfalls

The default client has no timeout set — with a slow or dead server, a request can hang for a very long time.

19. Java: Servlet Request Filter (Middleware)

Java

Intercepting HTTP traffic, logging execution time, and validation.

import jakarta.servlet.*;
import java.io.IOException;

public class LoggingFilter implements Filter {
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) 
            throws IOException, ServletException {
        long start = System.currentTimeMillis();
        chain.doFilter(req, res);
        long duration = System.currentTimeMillis() - start;
        System.out.println("Czas zapytania: " + duration + "ms");
    }
}

When to use

Useful for logging response times, authorization, or shared validation across many endpoints at once.

Common pitfalls

A filter that doesn't call chain.doFilter() blocks the whole request — easy to forget when adding early return conditions.

20. Java: Safe File Handling (NIO)

Java

Efficient copying and buffering of large files via streaming.

import java.nio.file.*;

public class FileManager {
    public static void copy(String source, String target) throws Exception {
        Path srcPath = Paths.get(source);
        Path destPath = Paths.get(target);
        Files.copy(srcPath, destPath, StandardCopyOption.REPLACE_EXISTING);
    }
}

When to use

Use it for operations on large files, where the older API (java.io.File) tends to be slower and less flexible.

Common pitfalls

REPLACE_EXISTING overwrites the target file without warning — if data safety matters, check whether the file exists before copying.