Example usage for java.lang ClassLoader hashCode

List of usage examples for java.lang ClassLoader hashCode

Introduction

In this page you can find the example usage for java.lang ClassLoader hashCode.

Prototype

@HotSpotIntrinsicCandidate
public native int hashCode();

Source Link

Document

Returns a hash code value for the object.

Usage

From source file:ClassLoaderUtils.java

/**
 * Show the class loader hierarchy for the given class loader.
 * @param cl class loader to analyze hierarchy for
 * @param lineBreak line break/* w  w w .  j  a  v  a 2  s .  c  om*/
 * @param tabText text to use to set tabs
 * @param indent nesting level (from 0) of this loader; used in pretty printing
 * @return a String showing the class loader hierarchy for this class
 */
private static String showClassLoaderHierarchy(ClassLoader cl, String lineBreak, String tabText, int indent) {
    if (cl == null) {
        ClassLoader ccl = Thread.currentThread().getContextClassLoader();
        return "context class loader=[" + ccl + "] hashCode=" + ccl.hashCode();
    }
    StringBuffer buf = new StringBuffer();
    for (int i = 0; i < indent; i++) {
        buf.append(tabText);
    }
    buf.append("[").append(cl).append("] hashCode=").append(cl.hashCode()).append(lineBreak);
    ClassLoader parent = cl.getParent();
    return buf.toString() + showClassLoaderHierarchy(parent, lineBreak, tabText, indent + 1);
}

From source file:net.geoprism.context.ServerInitializer.java

@Request
private static void startup(List<ServerContextListenerInfo> infos) {
    for (ServerContextListenerInfo info : infos) {
        try {//from   w w  w.  j  av a2s  . c o  m

            Class<?> clazz = LoaderDecorator.load(info.getClassName());
            Object newInstance = clazz.newInstance();

            try {
                ServerContextListener listener = (ServerContextListener) newInstance;
                listener.startup();
            } catch (ClassCastException e) {
                log.error("ClassCastException initializer", e);

                Class<? extends Object> class1 = newInstance.getClass();
                ClassLoader loader1 = class1.getClassLoader();

                log.debug("New instance class : " + class1.hashCode());
                log.debug("New instance class loader: " + loader1.hashCode());

                Class<? extends Object> class2 = ServerContextListener.class;
                ClassLoader loader2 = class2.getClassLoader();

                log.debug("Interface class : " + class2.hashCode());
                log.debug("New instance class loader: " + loader2.hashCode());

                clazz.getMethod("startup").invoke(newInstance);
            }

            log.debug("COMLPETE: " + info.getClassName() + ".setup();");
        } catch (Exception e) {
            log.error(e);

            throw new ProgrammingErrorException(
                    "Unable to startup the server context listener [" + info.getClassName() + "]", e);
        }
    }
}

From source file:net.geoprism.context.ServerInitializer.java

@Request
public static void destroy() {
    ServerContextListenerDocumentBuilder builder = new ServerContextListenerDocumentBuilder();
    List<ServerContextListenerInfo> infos = builder.read();

    Collections.reverse(infos);/*www  .  j  a v  a  2  s  . c  o  m*/

    for (ServerContextListenerInfo info : infos) {
        try {

            Class<?> clazz = LoaderDecorator.load(info.getClassName());
            Object newInstance = clazz.newInstance();

            try {
                ServerContextListener listener = (ServerContextListener) newInstance;
                listener.shutdown();
            } catch (ClassCastException e) {
                log.error("ClassCastException in ServerInitializer.shutdown", e);

                Class<? extends Object> class1 = newInstance.getClass();
                ClassLoader loader1 = class1.getClassLoader();

                log.debug("New instance class : " + class1.hashCode());
                log.debug("New instance class loader: " + loader1.hashCode());

                Class<? extends Object> class2 = ServerContextListener.class;
                ClassLoader loader2 = class2.getClassLoader();

                log.debug("Interface class : " + class2.hashCode());
                log.debug("New instance class loader: " + loader2.hashCode());

                clazz.getMethod("shutdown").invoke(newInstance);
            }

            log.debug("COMLPETE: " + info.getClassName() + ".shutdown();");
        } catch (Exception e) {
            log.error(e);

            throw new ProgrammingErrorException(
                    "Unable to shutdown the server context listener [" + info.getClassName() + "]", e);
        }
    }
}

From source file:com.opensymphony.xwork2.util.DefaultLocalizedTextProvider.java

/**
 * Finds the given resource bundle by it's name.
 * <p>/*w  w  w  . ja  v a 2s .co m*/
 * Will use <code>Thread.currentThread().getContextClassLoader()</code> as the classloader.
 * </p>
 *
 * @param aBundleName the name of the bundle (usually it's FQN classname).
 * @param locale      the locale.
 * @return the bundle, <tt>null</tt> if not found.
 */
@Override
public ResourceBundle findResourceBundle(String aBundleName, Locale locale) {
    ClassLoader classLoader = getCurrentThreadContextClassLoader();
    String key = createMissesKey(String.valueOf(classLoader.hashCode()), aBundleName, locale);

    if (missingBundles.contains(key)) {
        return null;
    }

    ResourceBundle bundle = null;
    try {
        if (bundlesMap.containsKey(key)) {
            bundle = bundlesMap.get(key);
        } else {
            bundle = ResourceBundle.getBundle(aBundleName, locale, classLoader);
            bundlesMap.putIfAbsent(key, bundle);
        }
    } catch (MissingResourceException ex) {
        if (delegatedClassLoaderMap.containsKey(classLoader.hashCode())) {
            try {
                if (bundlesMap.containsKey(key)) {
                    bundle = bundlesMap.get(key);
                } else {
                    bundle = ResourceBundle.getBundle(aBundleName, locale,
                            delegatedClassLoaderMap.get(classLoader.hashCode()));
                    bundlesMap.putIfAbsent(key, bundle);
                }
            } catch (MissingResourceException e) {
                LOG.debug("Missing resource bundle [{}]!", aBundleName, e);
                missingBundles.add(key);
            }
        } else {
            LOG.debug("Missing resource bundle [{}]!", aBundleName);
            missingBundles.add(key);
        }
    }
    return bundle;
}

From source file:com.opensymphony.xwork2.util.DefaultLocalizedTextProvider.java

/**
 * Add's the bundle to the internal list of default bundles.
 * <p>//w w  w  .  j  a va  2 s . c o m
 * If the bundle already exists in the list it will be readded.
 * </p>
 *
 * @param resourceBundleName the name of the bundle to add.
 */
@Override
public void addDefaultResourceBundle(String resourceBundleName) {
    //make sure this doesn't get added more than once
    final ClassLoader ccl = getCurrentThreadContextClassLoader();
    synchronized (XWORK_MESSAGES_BUNDLE) {
        List<String> bundles = classLoaderMap.get(ccl.hashCode());
        if (bundles == null) {
            bundles = new CopyOnWriteArrayList<>();
            classLoaderMap.put(ccl.hashCode(), bundles);
        }
        bundles.remove(resourceBundleName);
        bundles.add(0, resourceBundleName);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug(
                "Added default resource bundle '{}' to default resource bundles for the following classloader '{}'",
                resourceBundleName, ccl.toString());
    }
}

From source file:org.glowroot.agent.impl.BytecodeServiceImpl.java

@Override
public void preloadSomeSuperTypes(ClassLoader loader, @Nullable String className) {
    if (className == null) {
        return;/*w w w .j  a v a2s .c o  m*/
    }
    Set<String> preloadSomeSuperTypes = preloadSomeSuperTypesCache.get(className);
    if (preloadSomeSuperTypes.isEmpty()) {
        return;
    }
    Set<String> currentlyLoadingTypes = currentlyLoadingTypesHolder.get();
    boolean topLevel;
    if (currentlyLoadingTypes == null) {
        // using linked hash set so that top level class can be found as first element
        currentlyLoadingTypes = Sets.newLinkedHashSet();
        currentlyLoadingTypesHolder.set(currentlyLoadingTypes);
        topLevel = true;
    } else if (currentlyLoadingTypes.iterator().next().equals(className)) {
        // not top level, and need to abort the (nested) defineClass() that this is inside of,
        // otherwise the defineClass() that this is inside of will succeed, but then the top
        // level defineClass() will fail with "attempted duplicate class definition for name"
        throw new AbortPreload();
    } else {
        topLevel = false;
    }
    if (!currentlyLoadingTypes.add(className)) {
        // already loading className, prevent infinite loop / StackOverflowError, see
        // AnalyzedClassPlanBeeWithBadPreloadCacheIT
        return;
    }
    try {
        for (String superClassName : preloadSomeSuperTypes) {
            logger.debug("pre-loading super class {} for {}, in loader={}@{}", superClassName, className,
                    loader.getClass().getName(), loader.hashCode());
            try {
                Class.forName(superClassName, false, loader);
            } catch (ClassNotFoundException e) {
                logger.debug("super class {} not found (for sub-class {})", superClassName, className, e);
            } catch (LinkageError e) {
                // this can happen, e.g. ClassCircularityError, under strange circumstances,
                // see AnalyzedClassPlanBeeWithMoreBadPreloadCacheIT
                logger.debug("linkage error occurred while loading super class {} (for" + " sub-class {})",
                        superClassName, className, e);
            } catch (AbortPreload e) {
            }
        }
    } finally {
        if (topLevel) {
            currentlyLoadingTypesHolder.remove();
        } else {
            currentlyLoadingTypes.remove(className);
        }
    }
}

From source file:org.mule.module.logging.MuleLogFactory.java

public Log getInstance(String name) throws LogConfigurationException {
    final ClassLoader ccl = Thread.currentThread().getContextClassLoader();
    ConcurrentMap<String, Log> loggerMap = repository.get(ccl == null ? NO_CCL_CLASSLOADER : ccl.hashCode());

    if (loggerMap == null) {
        loggerMap = new ConcurrentHashMap<String, Log>();

        final ConcurrentMap<String, Log> previous = repository
                .putIfAbsent(ccl == null ? NO_CCL_CLASSLOADER : ccl.hashCode(), loggerMap);
        if (previous != null) {
            loggerMap = previous;/*ww  w  . j  av a 2 s . com*/
        }

        if (ccl != null) {
            // must save a strong ref to the PhantomReference in order for it to stay alive and work
            refs.put(new PhantomReference<ClassLoader>(ccl, referenceQueue), ccl.hashCode());
        }

    }

    Log instance = loggerMap.get(name);

    if (instance == null) {
        Logger logger = LoggerFactory.getLogger(name);
        if (logger instanceof LocationAwareLogger) {
            instance = new MuleLocationAwareLog((LocationAwareLogger) logger);
        } else {
            instance = new MuleLog(logger);
        }
        final Log previous = loggerMap.putIfAbsent(name, instance);
        if (previous != null) {
            // someone got there before us
            instance = previous;
        }
    }

    return instance;
}

From source file:org.rhq.core.pc.plugin.ClassLoaderManager.java

/**
 * Similar to {@link #obtainPluginClassLoader(String)}, however, the classloader to be returned
 * will have the given parent classloader (as opposed to having parent classloaders that follow the
 * plugin dependency graph hierarchy). This is used to support loading discovery components where
 * those discovery components need to use connections to the parent resource in order to perform their
 * discovery./* ww w .j av  a2 s.co  m*/
 * 
 * @param pluginName the name of the plugin where the discovery component can be found
 * @param parentClassLoader the parent classloader of the new classloader being created
 * @return the new plugin classloader
 * @throws PluginContainerException 
 */
public synchronized ClassLoader obtainDiscoveryClassLoader(String pluginName, ClassLoader parentClassLoader)
        throws PluginContainerException {

    String hash = pluginName + '-' + Integer.toHexString(parentClassLoader.hashCode());
    ClassLoader cl = this.discoveryClassLoaders.get(hash);
    if (cl == null) {
        URL pluginJarUrl = this.pluginNamesUrls.get(pluginName);
        if (log.isDebugEnabled()) {
            log.debug("Creating discovery classloader [" + hash + "] from URL [" + pluginJarUrl + ']');
        }
        cl = createClassLoader(pluginJarUrl, null, parentClassLoader);
        this.discoveryClassLoaders.put(hash, cl);
    }
    return cl;
}

From source file:org.wso2.carbon.utils.i18n.ResourceBundle.java

protected void loadProperties(String basename, ClassLoader loader, Locale locale, Locale defaultLocale) {
    // Check the cache first
    String loaderName = "";
    if (loader != null) {
        loaderName = ":" + loader.hashCode();
    }//from  w w w  .  j  av  a2 s .  co  m
    String cacheKey = basename + ":" + locale + ":" + defaultLocale + loaderName;
    Properties p = (Properties) propertyCache.get(cacheKey);
    basePropertyFileName = basename + PROPERTY_EXT;

    if (p == null) {
        // The properties were not found in the cache. Search the given locale first
        p = new Properties();
        if (locale != null) {
            p = loadProperties(basename, loader, locale, p);
        }

        // Search the default locale
        if (defaultLocale != null) {
            p = loadProperties(basename, loader, defaultLocale, p);
        }

        // Search for the basename
        p = merge(p, loadProperties(basePropertyFileName, loader));

        if (p == null) {
            throw new MissingResourceException("Cannot find resource for base name " + basePropertyFileName,
                    basePropertyFileName, "");
        }

        // Cache the properties
        propertyCache.put(cacheKey, p);

    }

    resourceProperties = p;
}