Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Understanding Java Wrapper Class Caching Mechanisms

Tech Jun 2 4

Java's wrapper classes implement caching mechanisms to optimize performance for commonly used values. Several numeric wrapper classes cache values within specific ranges:

  • Byte, Short, Integer, and Long cache values between -128 and 127
  • Character caches values from 0 to 127
  • Boolean directly returns either TRUE or FALSE instances

Integer caching implementation:

public static Integer valueOf(int num) {
    if (num >= IntegerCache.minVal && num <= IntegerCache.maxVal) {
        return IntegerCache.cachedValues[num + (-IntegerCache.minVal)];
    }
    return new Integer(num);
}

private static class IntegerCache {
    static final int minVal = -128;
    static final int maxVal;
    static final Integer[] cachedValues;
    
    static {
        int upper = 127;
        // Configuration logic for upper bound would go here
        maxVal = upper;
        
        cachedValues = new Integer[(maxVal - minVal) + 1];
        for (int k = 0; k < cachedValues.length; k++) {
            cachedValues[k] = new Integer(minVal + k);
        }
    }
}

The valueOf() method first checks if the input falls within the cached range. If so, it returns a pre-allocated object from the cache array. The array index calculation accounts for negative numbers by offsetting with the minimum cache value.

Character caching example:

public static Character valueOf(char ch) {
    if (ch <= 127) {
        return CharacterCache.predefinedChars[(int)ch];
    }
    return new Character(ch);
}

private static class CharacterCache {
    static final Character[] predefinedChars = new Character[128];
    
    static {
        for (int i = 0; i < predefinedChars.length; i++) {
            predefinedChars[i] = new Character((char)i);
        }
    }
}

Boolean optimization:

public static Boolean valueOf(boolean flag) {
    return flag ? Boolean.TRUE : Boolean.FALSE;
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.