A collection of high-performance Java utilities designed to enhance standard Java functionality. These utilities focus on:
- Memory efficiency and performance optimization
- Thread-safety and concurrent operations
- Enhanced collection implementations
- Simplified common programming tasks
- Deep object graph operations
Available on Maven Central.
This library has no dependencies on other libraries for runtime.
The.jarfile is ~700K and works with JDK 1.8 through JDK 24.
The .jar file classes are version 52 (JDK 1.8)
As of version 3.6.0 the library is built with the -parameters
compiler flag. Parameter names are now retained for tasks such as
constructor discovery (increased the jar size by about 10K.)
Table of Contents
- Cloud Native & Container Ready
- JDK Module Requirements
- Featured Utilities
- How java-util Compares
- Enterprise Security Features
- Core Components
- Integration and Module Support
- Feature Options
- Logging
- User Guide
Cloud Native & Container Ready
Optimized for modern cloud deployments and container environments:
Technical Characteristics:
- Minimal Footprint: ~700KB JAR
- Zero Runtime Dependencies: No transitive dependencies to manage, reducing classpath conflicts and container image complexity
- Fast Startup: JDK 8 bytecode (class file format 52) with instant classloading, optimized for serverless cold starts
- Thread-Safe: All concurrent collections designed for horizontal scaling in Kubernetes and containerized environments
- JPMS/OSGi Support: Works with jlink for custom JRE builds (<50MB runtime), compatible with OSGi frameworks (Karaf, Felix, Equinox)
Deployment Environments:
- Container platforms (Docker, Kubernetes, OpenShift)
- Serverless functions (AWS Lambda, Azure Functions, Google Cloud Functions, Cloud Run)
- Cloud infrastructure (ECS, EKS, AKS, GKE, Fargate, App Engine)
- Edge computing and microservices architectures
Security Benefits:
- Minimal attack surface with single artifact dependency tracking
- Uses
java.util.loggingonly (no Log4Shell exposure) - Air-gap and compliance-friendly for restricted environments
JDK Module Requirements
Required Modules
java.sql - Required for date/time conversions (java.sql.Timestamp and java.sql.Date)
- Impact: ~500KB footprint, includes JDBC API interfaces (no drivers required)
- Why: Core
Converterusesjava.sql.Timestampextensively for date/time type conversions - Headless containers: This adds ~500KB to your deployment but does NOT require database connectivity or JDBC drivers
Optional Modules (static dependencies)
java.xml - Optional for IOUtilities XML stream operations (javax.xml.stream.*)
- Only needed for XML-specific methods in
IOUtilities - Most library functionality works without it
- See
IOUtilitiesjavadoc for details
JPMS Module Descriptor
When using java-util as a JPMS module, add to your module-info.java:
requires com.cedarsoftware.util; // Automatically brings in java.sql // java.xml is marked as 'static' - not required at runtime
OSGi
The OSGi manifest automatically imports all required packages. Optional packages (javax.xml.stream) are marked as optional imports.
Featured Utilities
π DeepEquals - Complete Object Comparison
What: Compare any two Java objects for complete equality, handling all data types including cyclic references.
Why use it:
- β Works with any objects - no equals() method needed
- β Handles circular references and complex nested structures
- β Perfect for testing, debugging, and data validation
- β Secure error messages with automatic sensitive data redaction
- β Detailed difference reporting with path to mismatch
Quick example:
boolean same = DeepEquals.deepEquals(complexObject1, complexObject2); // With difference reporting Map<String, Object> options = new HashMap<>(); boolean same = DeepEquals.deepEquals(obj1, obj2, options); if (!same) { String diff = (String) options.get(DeepEquals.DIFF); System.out.println("Difference: " + diff); }
π Full documentation and options β
π― Converter - Universal Type Conversion
What: Convert between many Java types with a single API - no more scattered conversion logic.
Why use it:
- β
~1800 type conversions out of the box (use
.allAllSupportedConversions()to list them out) - β Extensible - add your own custom conversions
- β Handles complex types including temporal, arrays, and collections
Quick example:
Date date = Converter.convert("2024-01-15", Date.class); Long number = Converter.convert("42.7", Long.class); // Returns 43
π Full documentation and conversion matrix β
β° TTLCache - Self-Cleaning Time-Based Cache
What: A thread-safe cache that automatically expires entries after a time-to-live period, plus includes full LRU capability.
Why use it:
- β Automatic memory management - no manual cleanup needed
- β Prevents memory leaks from forgotten cache entries
- β Perfect for session data, API responses, and temporary results
Quick example:
TTLCache<String, User> userCache = new TTLCache<>(5, TimeUnit.MINUTES); userCache.put("user123", user); // Auto-expires in 5 minutes User cached = userCache.get("user123"); // Returns user or null if expired
π Full documentation and configuration β
π CompactMap - Self-Optimizing Storage
What: A Map implementation that automatically switches between compact and traditional storage based on size.
Why use it:
- β Significant memory reduction for small maps (under ~60 elements)
- β Automatically scales up for larger datasets
- β Drop-in replacement for HashMap - no code changes needed
Quick example:
Map<String, Object> map = new CompactMap<>(); // Starts compact map.put("key", "value"); // Uses minimal memory // Automatically expands when needed - completely transparent
π Full documentation and benchmarks β
π MultiKeyMap - Composite Key Mapping
What: Index objects with unlimited keys (decision variables). Useful for pricing tables, configuration trees, decision tables, arrays and collections as keys, matrix as key.
Why use it:
- β Composite keys without ceremony β Stop gluing keys into strings or writing boilerplate Pair/wrapper classes.
- β Real-world key shapes β Use arrays, collections, jagged multi-dimensional arrays, matrices/tensors, etc., as key components; deep equality & hashing mean βsame contentsβ truly equals βsame key.β
- β Cleaner, safer code β No more hand-rolled equals()/hashCode() on ad-hoc key objects. Fewer collision bugs, fewer βwhy doesnβt this look up?β moments.
- β Beats nested maps β One structure instead of Map<A, Map<B, V>>. Simpler reads/writes, simpler iteration, simpler mental model.
- β Follows same concurrency semantics as ConcurrentHashMap.
- β Map-like ergonomics β Familiar put/get/contains/remove semantics; drop-in friendly alongside the rest of java.util collections.
- β Fewer allocations β Avoid creating short-lived wrapper objects just to act as a key; reduce GC pressure versus βmake-a-key-object-per-call.β
- β Better iteration & analytics β Iterate entries once; no nested loops to walk inner maps when you just need all (k1,k2,β¦,v) tuples.
- β Easier indexing patterns β Natural fit for multi-attribute lookups (e.g., (tenantId, userId), (type, region), (dateBucket, symbol)).
- β Configurable case-insensitivity (case-retaining) β opt in to case-insensitive matching where you want it, keep exact matching where you donβtβall while preserving original casing for display/logging.
Quick examples:
Example 1 β Composite key that includes a small jagged array
// Composite key: [[1, 2], "some key"] -> value MultiKeyMap<String> map = new MultiKeyMap<>(); Object[] compositeKey = new Object[] { new int[]{1, 2}, "some key" }; map.put(compositeKey, "payload-123"); // Retrieve using a *new* array with the same contents (deep equality) String v1 = map.get(compositeKey); // v1 = "payload-123" // Standard Map operations work with the composite array key boolean present = map.containsKey(compositeKey); // true map.remove(compositeKey); map.containsKey(compositeKey); // false
Example 2 β Var-args style (no ambiguity with Map.put/get)
// Var-args API: putMultiKey(value, k1, k2, k3) and getMultiKey(k1, k2, k3) // Use this when you already have the distinct keys in hand. MultiKeyMap<String> map = new MultiKeyMap<>(); String tenantId = "acme"; long userId = 42L; String scope = "read:invoices"; // Value first by design (var-args must be last) map.putMultiKey("granted", tenantId, userId, scope); String perm = map.getMultiKey(tenantId, userId, scope); System.out.println(perm); // prints: granted boolean ok = map.containsMultiKey(tenantId, userId, scope); System.out.println(ok); // true map.removeMultiKey(tenantId, userId, scope); System.out.println(map.containsMultiKey(tenantId, userId, scope)); // false
π Full documentation and use cases β
π Plus Many More Utilities
From reflection helpers to graph traversal, concurrent collections to date utilities - java-util has you covered. Browse all utilities β
Why developers love these utilities:
- Zero dependencies - No classpath conflicts
- Null-safe - Handle edge cases gracefully
- High performance - Optimized for real-world usage
- JDK 8+ compatible - Works everywhere
- Production proven - Used in high-scale applications
How java-util Compares
| Feature | JDK Collections | Google Guava | Eclipse Collections | Apache Commons | java-util |
|---|---|---|---|---|---|
| Dependencies | None | 3+ libraries | 2+ libraries | Multiple | None |
| Jar Size | N/A | ~2.7MB | ~2.8MB | ~500KB each | ~700KB total |
| JDK Compatibility | 8+ | 11+ (latest) | 11+ | 8+ | 8+ |
| Null-Safe Concurrent | β | β | β | β | β ConcurrentMapNullSafe |
| Memory-Adaptive Collections | β | β | β | β | β CompactMap/Set |
| Case-Preserving Maps | β | β | β | Limited | β Retains original case |
| Universal Type Conversion | β | Limited | β | Limited | β ~1800 conversions |
| N-Dimensional Mapping | β | β οΈ Table (2D only) | β | β οΈ Limited | β MultiKeyMap (unlimited N-D) |
| Deep Object Comparison | β | Limited | β | β | β Handles cycles |
| Runtime Configuration | β | β | β | β | β 70+ feature options |
| TTL Caching | β | β | β | β | β + LRU combo |
| Thread-Safe with Nulls | β | β | β | β | β All concurrent types |
| JPMS/OSGi Ready | β | β οΈ | β | β οΈ | β Pre-configured |
| Security Controls | β | β | β | β | β Input validation |
Key Differentiators
π― Zero Dependencies: Unlike Guava (Checker Framework, Error Prone, J2ObjC) or Eclipse Collections (JUnit, SLF4J), java-util has zero runtime dependencies - no classpath conflicts ever.
π Null-Safe Concurrency: java-util is the only library providing thread-safe collections that handle null keys and values safely (ConcurrentHashMapNullSafe, ConcurrentSetNullSafe).
π§ Smart Memory Management: CompactMap and CompactSet automatically adapt from array-based storage (small size) to hash-based storage (large size) - optimal memory usage at every scale.
π Universal Conversion: Convert between any meaningful Java types - primitives, collections, dates, enums, custom objects. Other libraries require multiple dependencies to achieve the same coverage.
βοΈ Production Flexibility: 70+ runtime configuration options allow zero-downtime security hardening and environment-specific tuning that enterprise applications demand.
π Enterprise Security Features
java-util provides comprehensive security controls designed for enterprise environments where security compliance and threat mitigation are critical:
π‘οΈ Input Validation & DOS Protection
Configurable Resource Limits:
// Prevent memory exhaustion attacks System.setProperty("deepequals.max.collection.size", "1000000"); System.setProperty("stringutilities.max.repeat.total.size", "10485760"); System.setProperty("mathutilities.max.array.size", "1000000"); // Protect against ReDoS (Regular Expression Denial of Service) System.setProperty("dateutilities.regex.timeout.enabled", "true"); System.setProperty("dateutilities.regex.timeout.milliseconds", "1000");
π« Dangerous Class Protection
Block Access to Sensitive System Classes:
// Prevent reflection-based attacks System.setProperty("reflectionutils.dangerous.class.validation.enabled", "true"); // Blocks: Runtime, ProcessBuilder, System, Unsafe, ScriptEngine // Prevent sensitive field access System.setProperty("reflectionutils.sensitive.field.validation.enabled", "true"); // Blocks: password, secret, apikey, credential fields
π Cryptographic Security
Enforce Strong Crypto Parameters:
// PBKDF2 iteration requirements System.setProperty("encryptionutilities.min.pbkdf2.iterations", "100000"); System.setProperty("encryptionutilities.max.pbkdf2.iterations", "1000000"); // Salt and IV size validation System.setProperty("encryptionutilities.min.salt.size", "16"); System.setProperty("encryptionutilities.min.iv.size", "12");
π Network Security Controls
Protocol and Host Validation:
// Restrict allowed protocols System.setProperty("io.allowed.protocols", "https"); System.setProperty("urlutilities.allowed.protocols", "https"); // Prevent SSRF (Server-Side Request Forgery) System.setProperty("urlutilities.allow.internal.hosts", "false"); System.setProperty("urlutilities.max.download.size", "104857600"); // 100MB limit
π Security Audit & Monitoring
Comprehensive Logging:
// Enable detailed security logging System.setProperty("io.debug", "true"); System.setProperty("io.debug.detailed.urls", "true"); System.setProperty("io.debug.detailed.paths", "true");
π’ Zero-Downtime Security Hardening
Production-Safe Configuration:
- Feature flags: Enable/disable security features without code changes
- Gradual rollout: Test security features in staging before production
- Environment-specific: Different limits for dev/staging/production
- Compliance ready: Meet OWASP, SOC 2, ISO 27001 requirements
Example: Progressive Security Enablement
# Development (permissive) -Dreflectionutils.security.enabled=false # Staging (warning mode) -Dreflectionutils.security.enabled=true -Dreflectionutils.dangerous.class.validation.enabled=false # Production (full security) -Dreflectionutils.security.enabled=true -Dreflectionutils.dangerous.class.validation.enabled=true -Dreflectionutils.sensitive.field.validation.enabled=true
π Security Compliance
| Security Standard | java-util Coverage |
|---|---|
| OWASP Top 10 | β Injection prevention, DoS protection, Logging |
| CWE Mitigation | β CWE-22 (Path traversal), CWE-502 (Unsafe deserialization) |
| NIST Guidelines | β Input validation, Crypto parameter enforcement |
| SOC 2 Type II | β Audit logging, Access controls, Data protection |
Default Secure: All security features are disabled by default for backward compatibility, but can be enabled system-wide with zero code changes.
Core Components
| Component | Description |
|---|---|
| Sets | |
| CompactSet | Memory-efficient Set that dynamically adapts its storage structure based on size. |
| CaseInsensitiveSet | Set implementation with case-insensitive String handling. |
| ConcurrentSet | Thread-safe Set supporting null elements. |
| ConcurrentNavigableSetNullSafe | Thread-safe NavigableSet supporting null elements. |
| IdentitySet | High-performance Set using object identity (==) instead of equals(). Faster than Collections.newSetFromMap(new IdentityHashMap<>()). |
| ClassValueSet | High-performance Set optimized for fast Class membership testing using JVM-optimized ClassValue. |
| IntervalSet | Thread-safe interval set with O(log n) performance, automatically merges intervals, smart boundary handling for 20+ types, and you can add your own. |
| Maps | |
| CompactMap | Memory-efficient Map that dynamically adapts its storage structure based on size. |
| CaseInsensitiveMap | A Map wrapper that provides case-insensitive, case-retentive keys and inherits the features of the wrapped map (e.g., thread-safety from ConcurrentMap types, multi-key support from MultiKeyMap, sorted, thread-safe, allow nulls from ConcurrentNavigableMapNullSafe). |
| LRUCache | Thread-safe Least Recently Used cache with configurable eviction strategies. |
| TTLCache | Thread-safe Time-To-Live cache with optional size limits. |
| TrackingMap | A Map wrapper that tracks key access. Inherits features from wrapped Map, including thread-safety (ConcurrentMap types), sorted, thread-safe, with null support (ConcurrentNavigableMapNullSafe) |
| ConcurrentHashMapNullSafe | Thread-safe HashMap supporting null keys and values. |
| ConcurrentNavigableMapNullSafe | Thread-safe NavigableMap supporting null keys and values. |
| ClassValueMap | High-performance Map optimized for fast Class key lookups using JVM-optimized ClassValue. |
| MultiKeyMap | Concurrent map supporting multiple keys. |
| Lists | |
| ConcurrentList | High-performance bucket-based concurrent List and Deque with lock-free operations. |
| Utilities | |
| ArrayUtilities | Comprehensive array manipulation operations. |
| ByteUtilities | Byte array and hexadecimal conversion utilities. |
| ClassUtilities | Class relationship and reflection helper methods. |
| Converter | An extensive and extensible conversion utility with thousands of built-in transformations between common JDK types (Dates, Collections, Primitives, EnumSets, etc.). |
| DateUtilities | Advanced date parsing and manipulation. |
| DataGeneratorInputStream | Memory-efficient InputStream for generating test data on-the-fly with multiple generation modes (random, sequential, patterns, custom). |
| DeepEquals | Recursive object graph comparison. |
| EncryptionUtilities | Simplified encryption and checksum operations. |
| Executor | Streamlined system command execution. |
| GraphComparator | Object graph difference detection and synchronization. |
| IOUtilities | Enhanced I/O operations and streaming utilities. |
| MathUtilities | Extended mathematical operations. |
| ReflectionUtils | Optimized reflection operations. |
| RegexUtilities | Safe regex operations with ReDoS protection, pattern caching, and timeout enforcement. |
| StringUtilities | Extended String manipulation operations. |
| SystemUtilities | System and environment interaction utilities. |
| Traverser | Configurable object graph traversal. |
| TypeUtilities | Advanced Java type introspection and generic resolution utilities. |
| UniqueIdGenerator | Distributed-safe unique identifier generation. |
Integration and Module Support
JPMS (Java Platform Module System)
This library is fully compatible with JPMS, commonly known as Java Modules. It includes a module-info.class file that
specifies module dependencies and exports.
OSGi
This library also supports OSGi environments. It comes with pre-configured OSGi metadata in the MANIFEST.MF file, ensuring easy integration into any OSGi-based application.
Using in an OSGi Runtime
The jar already ships with all necessary OSGi headers and a module-info.class. No Import-Package entries for java.* packages are required when consuming the bundle.
To add the bundle to an Eclipse feature or any OSGi runtime simply reference it:
<plugin id="com.cedarsoftware.java-util" version="LATEST_VERSION"/>
Both of these features ensure that our library can be seamlessly integrated into modular Java applications, providing robust dependency management and encapsulation.
Maven and Gradle Integration
To include in your project:
Gradle
implementation 'com.cedarsoftware:java-util:LATEST_VERSION'Maven
<dependency> <groupId>com.cedarsoftware</groupId> <artifactId>java-util</artifactId> <version>LATEST_VERSION</version> </dependency>
π Framework Integration Examples
For comprehensive framework integration examples including Spring, Jakarta EE, Spring Boot Auto-Configuration, Microservices, Testing, and Performance Monitoring.
Key integrations include:
- Spring Framework - Configuration beans and case-insensitive property handling
- Jakarta EE/JEE - CDI producers and validation services
- Spring Boot - Auto-configuration with corrected cache constructors
- Microservices - Service discovery and cloud-native configuration
- Testing - Enhanced test comparisons with DeepEquals
- Monitoring - Micrometer metrics integration
Feature Options
java-util provides 70+ runtime configuration options via system properties, enabling:
- Zero-downtime security hardening - Enable security features without code changes
- Environment-specific tuning - Different limits for development vs. production
- Gradual rollout strategies - Test new security features with feature flags
- Compliance flexibility - Meet varying regulatory requirements across deployments
All security features are disabled by default for backward compatibility.
π View complete feature options reference β
Logging
Because java-util has no dependencies on other libraries, java-util uses the Java built-in java.util.logging for all output. See the
user guide for ways to route
these logs to SLF4J or Log4j 2.
User Guide
View detailed documentation on all utilities.
See changelog.md for revision history.