Search code examples
javagenericsportabilitythread-local

Porting JDK1.5 ThreadLocal code to JDK1.4


I have below piece code which runs on JDK5

private static ThreadLocal<String> messages = new ThreadLocal<String>();
private static ThreadLocal<Boolean> dontIntercept = new ThreadLocal<Boolean>() {
    @Override
    protected Boolean initialValue() {
        return Boolean.FALSE;
        }
};

I wish to run it on JDK1.4. Please advice what changes will be required


Solution

    • Remove generics.
    • Remove covariant return.
    • Remove @Override annotation.

    So

    private static final ThreadLocal messages = new ThreadLocal();
    private static final ThreadLocal dontIntercept = new ThreadLocal() {
        protected Object initialValue() {
            return Boolean.FALSE;
        }
    };
    

    When using

    • Cast value back to Boolean.
    • Unbox with .booleanValue().
    • Box with Boolean.valueOf.