Example usage for java.lang.ref Reference get

List of usage examples for java.lang.ref Reference get

Introduction

In this page you can find the example usage for java.lang.ref Reference get.

Prototype

@HotSpotIntrinsicCandidate
public T get() 

Source Link

Document

Returns this reference object's referent.

Usage

From source file:org.nextframework.controller.CachedIntrospectionResults.java

/**
 * We might use this from the EJB tier, so we don't want to use synchronization.
 * Object references are atomic, so we can live with doing the occasional
 * unnecessary lookup at startup only./*from   w w  w . j av a2s .co  m*/
 */
@SuppressWarnings("unchecked")
static CachedIntrospectionResults forClass(Class clazz) throws BeansException {
    CachedIntrospectionResults results = null;
    Object value = classCache.get(clazz);
    if (value instanceof Reference) {
        Reference ref = (Reference) value;
        results = (CachedIntrospectionResults) ref.get();
    } else {
        results = (CachedIntrospectionResults) value;
    }
    if (results == null) {
        // can throw BeansException
        results = new CachedIntrospectionResults(clazz);
        boolean cacheSafe = isCacheSafe(clazz);
        if (logger.isDebugEnabled()) {
            logger.debug("Class [" + clazz.getName() + "] is " + (!cacheSafe ? "not " : "") + "cache-safe");
        }
        if (cacheSafe) {
            classCache.put(clazz, results);
        } else {
            classCache.put(clazz, new WeakReference(results));
        }
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("Using cached introspection results for class [" + clazz.getName() + "]");
        }
    }
    return results;
}

From source file:org.paxle.core.doc.impl.CommandTracker.java

/**
 * @see Thread#run()/*from  w  w  w  .  j  ava  2 s.c  om*/
 */
@Override
public void run() {
    try {
        while (!this.isInterrupted()) {
            try {
                /* Check for unreferenced ICommands.
                 * 
                 * Command that are accessible via this queue are not referenced 
                 * anywhere in the runtime.
                 * 
                 * This should only occur if a component has forgotten to call
                 * ICommandTracker.commandDestroyed(...)
                 */
                Reference<? extends ICommand> commandRef = this.refQueue.remove(CLEANUP_DELAY.longValue());
                if (commandRef != null) {
                    this.logger.error(
                            "Command was destroyed without calling ICommandTracker.commandDestroyed(...)");

                    ICommand command = commandRef.get();
                    if (command != null) {
                        // we should never get in here ...
                        this.logger.error("Unexpected stat. commandRef.get() returned not null");
                    } else {
                        Long commandID = null;
                        URI commandURI = null;
                        try {
                            w.lock();
                            Iterator<Map.Entry<Long, WeakReference<ICommand>>> commandIDIter = this.commandIDTable
                                    .entrySet().iterator();
                            while (commandIDIter.hasNext()) {
                                Map.Entry<Long, WeakReference<ICommand>> entry = commandIDIter.next();
                                if (entry.getValue().equals(commandRef)) {
                                    commandID = entry.getKey();
                                    commandIDIter.remove();
                                    break;
                                }
                            }

                            Iterator<Map.Entry<URI, WeakReference<ICommand>>> commandURIIter = this.commandLocationTable
                                    .entrySet().iterator();
                            while (commandIDIter.hasNext()) {
                                Map.Entry<URI, WeakReference<ICommand>> entry = commandURIIter.next();
                                if (entry.getValue().equals(commandRef)) {
                                    commandURI = entry.getKey();
                                    commandURIIter.remove();
                                    break;
                                }
                            }
                        } finally {
                            w.unlock();
                        }

                        this.logger.warn(String.format("Command [%06d] removed without calling destroy: %s",
                                commandID, (commandURI == null) ? "unknown" : commandURI.toASCIIString()));
                    }
                }

                /* Check for to old destroyed ICommands.
                 * 
                 */
                if (!this.destroyedCommandMap.isEmpty()) {
                    long maxage = System.currentTimeMillis() - MAX_HOLDBACK_TIME.longValue();

                    synchronized (this.destroyedCommandMap) {

                        while (!this.destroyedCommandMap.isEmpty()
                                && this.destroyedCommandMap.getFirst().destroyedTime.longValue() < maxage) {
                            // remove the next command
                            DestroyedCommandData destoryedCommand = this.destroyedCommandMap.removeFirst();

                            ICommand command = destoryedCommand.command;
                            Long commandID = Long.valueOf(command.getOID());
                            URI commandURI = command.getLocation();

                            // removing the outdated command from all lists
                            WeakReference<ICommand> cmdRef = null;
                            this.commandLocationTable.remove(commandURI);
                            cmdRef = this.commandIDTable.remove(commandID);
                            if (cmdRef != null)
                                cmdRef.clear();

                            this.logger.debug(String.format("Command [%06d] removed from destroyed map: %s",
                                    commandID, (commandURI == null) ? "unknown" : commandURI.toASCIIString()));
                        }
                    }
                }
            } catch (Throwable e) {
                if (e instanceof InterruptedException)
                    throw (InterruptedException) e;
                this.logger.error(String.format("Unexpected '%s' while cleaning up destroyed commands.",
                        e.getClass().getName()), e);
            }
        }
    } catch (InterruptedException e) {
        this.logger.info("Thread was interrupted");
    }
}

From source file:org.pentaho.reporting.engine.classic.core.util.WeakReferenceList.java

/**
 * Returns the child stored at the given index. If the child has been garbage collected, it gets restored using the
 * restoreChild function./*from  w  w w.j a  v a2 s.  c  o m*/
 *
 * @param index
 *          the index.
 * @return the object.
 */
public Object get(final int index) {
    if (isMaster(index)) {
        return master;
    } else {
        final Reference<T> ref = childs[getChildPos(index)];
        if (ref == null) {
            throw new IllegalStateException("State: " + index);
        }
        T ob = ref.get();
        if (ob == null) {
            ob = restoreChild(index);
            childs[getChildPos(index)] = createReference(ob);
        }
        return ob;
    }
}

From source file:org.pentaho.reporting.engine.classic.core.util.WeakReferenceList.java

public T getRaw(final int index) {
    if (isMaster(index)) {
        return master;
    } else {//from w  w  w.j  a  va  2 s.co m
        final Reference<T> ref = childs[getChildPos(index)];
        if (ref == null) {
            throw new IllegalStateException("State: " + index);
        }
        return ref.get();
    }
}

From source file:org.pentaho.ui.xul.binding.DefaultBinding.java

protected PropertyChangeListener setupBinding(final Reference a, final String va, final Reference b,
        final String vb, final Direction dir) {
    if (a.get() == null || va == null) {
        handleException(new BindingException("source bean or property is null"));
    }/*from ww  w  . j  a va 2s .co m*/
    if (!(a.get() instanceof XulEventSource)) {
        handleException(new BindingException(
                "Binding error, source object " + a.get() + " not a XulEventSource instance"));
    }
    if (b.get() == null || vb == null) {
        handleException(new BindingException("target bean or property is null"));
    }
    Method sourceGetMethod = BindingUtil.findGetMethod(a.get(), va);

    Class getterClazz = BindingUtil.getMethodReturnType(sourceGetMethod, a.get());
    getterMethods.push(sourceGetMethod);

    // find set method
    final Method targetSetMethod = BindingUtil.findSetMethod(b.get(), vb, getterClazz);

    // setup prop change listener to handle binding
    PropertyChangeListener listener = new PropertyChangeListener() {
        public void propertyChange(final PropertyChangeEvent evt) {
            final PropertyChangeListener cThis = this;
            if (evt.getPropertyName().equalsIgnoreCase(va)) {
                try {
                    Object targetObject = b.get();
                    if (targetObject == null) {
                        logger.debug("Binding target was Garbage Collected, removing propListener");
                        DefaultBinding.this.destroyBindings();
                        return;
                    }

                    Object value = doConversions(evt.getNewValue(), dir);
                    final Object finalVal = evaluateExpressions(value);

                    logger.debug("Setting val: " + finalVal + " on: " + targetObject);
                    targetSetMethod.invoke(targetObject, finalVal);

                } catch (Exception e) {
                    logger.debug(e);
                    handleException(new BindingException("Error invoking setter method ["
                            + targetSetMethod.getName() + "] on target: " + target.get(), e));
                }
            }
        }
    };
    ((XulEventSource) a.get()).addPropertyChangeListener(listener);

    return listener;
}

From source file:org.srs.vfs.VfsSoftCache.java

@Override
public V getFile(final Path fileName) {
    lock.lock();/*www  .j  av a  2 s  .  c om*/
    try {
        final Reference<V> ref = virtualFileSystemCache.get(fileName);
        if (ref == null) {
            return null;
        }

        final V fo = ref.get();
        if (fo == null) {
            removeFile(fileName);
        }
        return fo;
    } finally {
        lock.unlock();
    }
}

From source file:org.tinygroup.beanwrapper.CachedIntrospectionResults.java

/**
 * Create CachedIntrospectionResults for the given bean class.
 * <P>We don't want to use synchronization here. Object references are atomic,
 * so we can live with doing the occasional unnecessary lookup at startup only.
 * @param beanClass the bean class to analyze
 * @return the corresponding CachedIntrospectionResults
 * @throws BeansException in case of introspection failure
 *///from   www  . ja v a  2  s.c  om
static CachedIntrospectionResults forClass(Class beanClass) throws BeansException {
    CachedIntrospectionResults results = null;
    Object value = classCache.get(beanClass);
    if (value instanceof Reference) {
        Reference ref = (Reference) value;
        results = (CachedIntrospectionResults) ref.get();
    } else {
        results = (CachedIntrospectionResults) value;
    }
    if (results == null) {
        // can throw BeansException
        results = new CachedIntrospectionResults(beanClass);
        if (ClassUtils.isCacheSafe(beanClass, CachedIntrospectionResults.class.getClassLoader())
                || isClassLoaderAccepted(beanClass.getClassLoader())) {
            classCache.put(beanClass, results);
        } else {
            if (logger.isDebugEnabled()) {
                logger.debug("Not strongly caching class [" + beanClass.getName()
                        + "] because it is not cache-safe");
            }
            classCache.put(beanClass, new WeakReference(results));
        }
    }
    return results;
}

From source file:org.wymiwyg.commons.util.dirbrowser.ZipPathNode.java

/**
 * @return//  w ww . j  av  a2 s  .  c o m
 */
public String[] list() {
    Reference currentRef = (Reference) listCache.get(this);
    if (currentRef != null) {
        String[] values = (String[]) currentRef.get();
        if (values != null) {
            return values;
        }
    }
    Enumeration jarEntries = file.entries();
    String name = entryName;
    if (!name.equals("") && name.charAt(name.length() - 1) != '/') {
        name = name + "/";
    }
    Set resultList = new HashSet();
    while (jarEntries.hasMoreElements()) {
        ZipEntry current = (ZipEntry) jarEntries.nextElement();
        String currentName = current.getName();
        if (logger.isDebugEnabled()) {
            logger.debug("evaluating: " + current);
        }
        if ((currentName.length() > name.length()) && (currentName.startsWith(name))) {
            String subPath = currentName.substring(name.length());
            if (subPath.length() > 0) {
                int slashPos = subPath.indexOf('/');
                if (slashPos == -1) {
                    resultList.add(subPath);
                } else {
                    resultList.add(subPath.substring(0, slashPos + 1));
                }

            }
        }

    }
    String[] result = (String[]) resultList.toArray(new String[resultList.size()]);
    listCache.put(this, new WeakReference(result));
    return result;
}

From source file:xbird.storage.index.Paged.java

/**
 * getPage returns the page specified by pageNum.
 *//*from  www  .  j  a  v  a 2s . c  o  m*/
protected final Page getPage(long pageNum) throws DbException {
    Page p = null;
    // if not check if it's already loaded in the page cache
    Reference<Page> ref = _pages.get(pageNum); // Check if required page is in the volatile cache
    if (ref != null) {
        p = ref.get();
    }
    if (p == null) {
        // if still not found we need to create it and add it to the page cache.
        p = new Page(pageNum);
        try {
            p.read(); // Load the page from disk if necessary
        } catch (IOException e) {
            throw new DbException(e);
        }
        _pages.put(pageNum, new WeakReference<Page>(p));
    }
    return p;
}