0

我在 groovy javadocs 中找到了这个类(Holder),但是 javadoc 是空的……有人知道它的作用吗?
似乎它像ThreadLocal一样工作,如果是,哪个更好?有什么优点?有什么坏处?

干杯

4

1 回答 1

0

我认为该课程已从主分支中删除。

我可以发布源代码:

/* Copyright 2011 SpringSource.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package grails.util;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Burt Beckwith
 * @since 2.0
 */
public class Holder<T> {

    private Map<Integer, T> instances = new ConcurrentHashMap<Integer, T>();
    // TODO remove mappedOnly and singleton
    private T singleton;
    private String name;

    public Holder(String name) {
        this.name = name;
    }

    public T get() {
        return get(false);
    }

    public T get(boolean mappedOnly) {
        T t = instances.get(getClassLoaderId());
        if (t != null) {
            return t;
        }

        t = lookupSecondary();
        if (t != null) {
            return t;
        }

//        t = instances.get(System.identityHashCode(getClass().getClassLoader()));
        if (t == null && !mappedOnly) {
            t = singleton;
        }
        return t;
    }

    protected T lookupSecondary() {
        // override in subclass if needed
        return null;
    }

    public void set(T t) {
        int id = getClassLoaderId();
        int thisClassLoaderId = System.identityHashCode(getClass().getClassLoader());
        if (t == null) {
            instances.remove(id);
            instances.remove(thisClassLoaderId);
        }
        else {
            instances.put(id, t);
            instances.put(thisClassLoaderId, t);
        }
        singleton = t;
    }

    private int getClassLoaderId() {
        return System.identityHashCode(Thread.currentThread().getContextClassLoader());
    }
}
于 2012-07-31T14:50:59.720 回答