Skip to content
StackPractices

Tag: java

Browse 110 practical software engineering resources tagged with "java". Discover code recipes, design patterns, documentation templates, and in-depth guides to help you build, deploy, and maintain production-ready solutions involving java.

Create API Documentation with OpenAPI

Generate interactive API docs from OpenAPI specs using Swagger UI, Redoc, and native tools in Python, JavaScript, and Java.

Implement API Logging and Audit Trails

Set up thorough request/response logging and audit trails for APIs with structured output, correlation IDs, and compliance considerations.

Implement a GraphQL API

Build a production-ready GraphQL API with type-safe schemas, resolvers, and query optimization in Python, JavaScript, and Java.

Handle Errors in APIs

Patterns for consistent, predictable API error handling across multiple languages and frameworks.

Input Validation

How to validate user input safely using schemas, type checking, and sanitization across Python, JavaScript, and Java.

Logging

How to implement structured, level-based logging across Python, JavaScript, and Java with what works for production observability.

Build Real-Time Notifications with WebSockets

Implement a real-time notification system using WebSockets and Redis pub/sub for broadcasting messages across clients.

Send Emails with SMTP

How to send transactional and bulk emails securely using SMTP with template support.

WebSocket Server

How to build a WebSocket server for bidirectional real-time communication, with connection management, message broadcasting, and heartbeat keepalive.

Dependency Injection

Implement dependency injection to write testable, decoupled code across languages and frameworks.

Configure Caffeine Cache in Java with Eviction Policies

Set up Caffeine cache in a Java application with size-based, time-based, and weighted eviction policies for high-performance local caching.

Use Spring Cache Annotations with Redis Backend

Apply Spring's @Cacheable, @CachePut, and @CacheEvict annotations with a Redis cache manager for declarative caching in Java applications.

Compose Asynchronous Pipelines with Java CompletableFuture

Build non-blocking async pipelines in Java using CompletableFuture with thenCompose, thenCombine, allOf, anyOf, exception handling, timeouts, and custom thread pools.

Scale Concurrent Applications with Java Virtual Threads

Scale Java applications with virtual threads from Project Loom. Use Thread.ofVirtual, Executors.newVirtualThreadPerTaskExecutor, structured concurrency, and scoped values.

Caching & Memoization

How to cache expensive computations and API responses using in-memory, LRU, and distributed caches across Python, JavaScript, and Java.

Convert CSV to JSON

How to convert CSV data to JSON format in Python, Java, and JavaScript.

Convert JSON to CSV

How to convert JSON data to CSV format in Python, Java, and JavaScript.

Diff JSON Objects

How to compare two JSON objects and find differences in Python, Java, and JavaScript.

Flatten and Unflatten Nested Objects

How to convert nested objects to flat key-value pairs and back again, with dot-notation, bracket notation, and custom separator support.

Format Phone Numbers

How to format and validate phone numbers in Python, Java, and JavaScript.

Generate URL Slugs

How to generate clean, URL-friendly slugs from strings in multiple programming languages.

Merge JSON Files

How to merge multiple JSON files into a single object or array in Python, Java, and JavaScript.

Parse Command Line Arguments

How to parse command line arguments in Python, Java, and Node.js CLI applications.

Parse CSV Files

How to parse CSV files in Python, Java, and JavaScript with practical code examples.

Parse Excel Files

How to read and write Excel (.xlsx) files in Python, Java, and JavaScript.

Parse JSON

How to parse JSON strings into native data structures across multiple programming languages.

Parse Log Files

How to parse and analyze server log files using Python, Java, and JavaScript.

Parse Markdown Files

How to parse Markdown to HTML and extract structured data in Python, Java, and JavaScript.

Parse PDF Files

How to extract text and metadata from PDF files in Python, Java, and JavaScript.

Parse TOML Files

How to parse TOML configuration files in Python, Java, and JavaScript.

Parse XML Files

How to parse XML documents in Python, Java, and JavaScript with practical code examples.

Parse YAML Files

How to parse YAML configuration files in Python, Java, and JavaScript.

Regular Expressions

How to use regular expressions for pattern matching, validation, and text extraction across Python, JavaScript, and Java.

Serialize and Deserialize Data

How to serialize and deserialize data in JSON, XML, and YAML across Python, Java, and JavaScript.

Sort an Array

How to sort arrays and lists in ascending, descending, and custom order across multiple languages.

Truncate Text

How to truncate text with ellipsis and word boundaries in Python, Java, and JavaScript.

URL Encoding

How to encode and decode URLs, query parameters, and path segments safely across Python, JavaScript, and Java.

Validate JSON Schema

How to validate JSON data against schemas in Python, Java, and JavaScript.

Connect to MySQL

How to connect to MySQL databases in Python, JavaScript, and Java.

Connect to PostgreSQL

How to connect to PostgreSQL databases in Python, JavaScript, and Java.

Connect to Redis

How to connect to Redis and perform basic operations in Python, JavaScript, and Java.

Execute Raw SQL

How to execute raw SQL queries safely with parameterized statements.

Use ORM for CRUD

How to perform CRUD operations using ORMs in Python, JavaScript, and Java.

Health Check Endpoint

How to implement a production-ready health check endpoint for monitoring and load balancers.

Parse and Validate YAML/JSON Configuration

How to parse and validate application configuration files using YAML and JSON schemas.

Compress and Decompress Files

How to handle ZIP, GZIP, and TAR archives programmatically.

Copy and Move Files

How to copy and move files across platforms safely and efficiently.

File Upload Validation

How to handle file uploads securely with size, type, and content validation.

Generate PDFs

How to generate PDF documents programmatically from HTML, templates, or raw data.

Generate Temporary Files

How to create temporary files and directories safely with automatic cleanup across Python, Node.js, Java, and Bash.

Read Large Files

How to read large files efficiently without running out of memory.

Rotate Log Files

How to implement log rotation by size, date, and count to prevent disk exhaustion across Python, Node.js, Java, and Linux systems.

Watch File Changes

How to monitor file system changes in real time.

Write Large Files

How to write large files efficiently using buffered and streaming output.

Consume Kafka Topics with Spring Boot Stream Listeners

Build Kafka consumers in Spring Boot using @KafkaListener annotations, concurrent consumers, error handlers, DLQ patterns, and batch listeners with manual acknowledgment.

Custom Health Checks with Spring Boot Actuator

How to implement custom health indicators with Spring Boot Actuator, including database, Redis, external API checks, and Kubernetes readiness probes.

Expose Metrics with Micrometer and Prometheus

How to expose custom application metrics using Micrometer and Prometheus in Spring Boot, including counters, gauges, timers, and histograms.

Escape HTML Entities

How to escape HTML entities to prevent XSS attacks in Python, Java, and JavaScript.

Detect Bugs in Java with SpotBugs Static Analysis

How to configure SpotBugs for Maven and Gradle, interpret bug patterns, suppress false positives, and integrate with CI/CD pipelines.

Sanitize User Input

How to sanitize and validate user input in Python, Java, and JavaScript to prevent injection attacks.

Generate Test Data

How to generate realistic, deterministic test data with Faker, factory-boy, and type-aware generators for reliable test suites in Python, JavaScript, and Java.

JUnit5 Soft Assertions with AssertJ

How to use AssertJ soft assertions in JUnit5 to collect multiple assertion failures in a single test instead of stopping at the first failure.

Java Testcontainers Integration Tests

How to use Testcontainers in JUnit5 to spin up real Postgres, Redis, and Kafka containers for integration tests that are reliable and reproducible.

Stub External HTTP Services with WireMock

How to use WireMock in Java tests to stub external HTTP services, including response templating, delay simulation, and stateful mock behavior.

Multi-Tenant Data Isolation Pattern

Isolate tenant data in shared infrastructure using row-level security, schema-per-tenant, or database-per-tenant strategies. A pattern for SaaS applications.

Pipes and Filters Pattern

Chain processing steps with independent filters connected by pipes. A pattern for data transformation pipelines where each step is reusable and composable.

Federated Identity Pattern

Delegate authentication to external identity providers. A pattern for integrating OAuth2, OIDC, SAML, and SSO across multiple services and organizations.

Voucher Pattern

Validate claims and delegate access using signed vouchers without exposing sensitive data. A security pattern for token-based authorization between services.

Abstract Factory Pattern

Create families of related objects without specifying concrete classes. A creational design pattern for consistent object families.

Adapter Pattern

Convert the interface of a class into another interface clients expect. A structural design pattern for interface compatibility.

Bridge Pattern

Decouple an abstraction from its implementation so both can vary independently. A structural design pattern for platform independence.

Builder Pattern

Construct complex objects step by step. A creational design pattern for readable, configurable object construction.

Cache-Aside Pattern

Load data into the cache on demand from the backing store. A caching pattern that gives the application full control over what and when to cache.

Chain of Responsibility Pattern

Pass requests along a chain of handlers until one handles it. A behavioral design pattern for decoupling senders and receivers.

Circuit Breaker Pattern

Prevent cascading failures by stopping requests to failing services. An architectural pattern for resilient distributed systems.

Command Pattern

Encapsulate a request as an object, letting you parameterize clients with queues, logs, and undoable operations. A behavioral design pattern.

Composite Pattern

Compose objects into tree structures to represent part-whole hierarchies. A structural design pattern for treating individual objects and compositions uniformly.

CQRS Pattern

Separate read and write operations into different models, optimizing each for their specific workload. A data pattern for scalable systems.

Decorator Pattern

Add new functionality to objects dynamically by wrapping them. A structural design pattern for flexible behavior extension.

Dependency Injection Pattern

Supply dependencies from outside rather than creating them internally. An architectural pattern for decoupled, testable code.

Event Sourcing Pattern

Store the state of an application as a sequence of events rather than storing only the current state. An architectural pattern for audit-friendly systems.

Factory Pattern

Create objects without specifying the exact class to instantiate. A creational design pattern for flexible object creation.

Flyweight Pattern

Share objects to support large numbers of fine-grained objects efficiently. A structural design pattern for memory optimization.

Interpreter Pattern

Define a representation for a language's grammar along with an interpreter that uses the representation to interpret sentences. A behavioral design pattern for mini-languages.

Iterator Pattern

Provide a way to access elements of a collection sequentially without exposing its underlying representation. A behavioral design pattern for traversal.

Marker Interface Pattern

Use empty interfaces as metadata tags to signal properties or capabilities at compile time and runtime, enabling type-safe checks without modifying class behavior.

Mediator Pattern

Define an object that encapsulates how a set of objects interact. A behavioral design pattern for reducing chaotic dependencies.

Memento Pattern

Capture and restore an object's internal state without violating encapsulation. A behavioral design pattern for undo/redo.

MVC Pattern

Separate application into Model, View, and Controller components. An architectural design pattern for organized, maintainable code.

Observer Pattern

Define a subscription mechanism to notify multiple objects about events. A behavioral design pattern for event-driven communication.

Prototype Pattern

Create new objects by copying existing ones. A creational design pattern for cloning and object duplication.

Proxy Pattern

Provide a surrogate or placeholder for another object to control access to it. A structural design pattern for access control, lazy loading, and logging.

Read-Through Cache Pattern

A transparent cache layer that intercepts read requests, fetches from the data source on miss, and populates the cache automatically.

Refresh-Ahead Cache Pattern

Proactively refresh cache entries before they expire to eliminate cache misses on hot keys and maintain consistent read latency.

Repository Pattern

Abstract data access logic behind a clean interface. An architectural design pattern for testable, maintainable data layers.

Retry Pattern

Retry an operation that has failed with transient errors, using configurable strategies like fixed delay, exponential backoff, or circuit breaker integration.

Saga Pattern

Manage distributed transactions across multiple services by chaining local transactions with compensating actions for rollbacks. A microservices pattern.

Singleton Pattern

Ensure a class has only one instance and provide global access to it. A creational design pattern for controlled object creation.

State Pattern

Allow an object to alter its behavior when its internal state changes. A behavioral design pattern for finite state machines.

Strategy Pattern

Define a family of algorithms, encapsulate each one, and make them interchangeable. A behavioral design pattern for flexible behavior selection.

Template Method Pattern

Define the skeleton of an algorithm in a base class, letting subclasses override specific steps without changing the algorithm's structure. A behavioral design pattern.

Timeout Pattern

Prevent operations from hanging indefinitely by enforcing a maximum execution time. A resilience pattern for predictable response times.

Two-Level Cache Pattern

Combine an L1 in-memory cache with an L2 distributed cache to reduce latency for hot keys while maintaining cache consistency across instances.

Visitor Pattern

Represent an operation to be performed on elements of an object structure without changing the classes of the elements. A behavioral design pattern.

Write-Behind Cache Pattern

Write to cache synchronously and persist to the database asynchronously for high-throughput write workloads with eventual consistency.

Write-Through Cache Pattern

Synchronously write to both cache and backing store so the cache always has the latest data without TTL-based invalidation.

Thread Pool Sizing Template

Template for documenting thread pool configuration per service: pool type selection, sizing formulas, CPU vs I/O bound tuning, queue strategies, rejection policies, monitoring metrics, and tuning examples for Java, Python, Go, and Node.js.

Complete Guide to Java Concurrency

Master Java concurrency in production. Covers threads, locks, CompletableFuture, virtual threads, executors, concurrent collections, memory model, and patterns for high-throughput parallel applications.

JUnit 5: Extensions, Parameterized Tests, Dynamic Tests

Master JUnit 5 for modern Java testing: extensions model, parameterized tests, dynamic tests, test interfaces, lifecycle, conditional execution, and JUnit Platform integration.

Testcontainers: Real Dependencies in Integration Tests

Master Testcontainers for integration testing with real databases, message brokers, and APIs. Covers Java, Python, and Node.js with Docker-based test fixtures.