Example usage for java.lang.ref SoftReference get

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

Introduction

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

Prototype

public T get() 

Source Link

Document

Returns this reference object's referent.

Usage

From source file:org.atricore.idbus.kernel.main.databinding.JAXBUtils.java

/**
 * Create a JAXBContext using the contextPackages
 *
 * @param contextPackages Set<String>
 * @param cl              ClassLoader//from w ww.  j ava  2  s. c om
 * @param forceArrays     boolean (true if JAXBContext must include all arrays)
 * @param properties      Map of properties for the JAXBContext.newInstance creation method
 * @param classRefs       List of class references
 * @return JAXBContextValue (JAXBContext + constructionType)
 * @throws javax.xml.bind.JAXBException
 */
private static JAXBContextValue createJAXBContextValue(TreeSet<String> contextPackages, ClassLoader cl,
        boolean forceArrays, Map<String, ?> properties, List<String> classRefs) throws JAXBException {

    JAXBContextValue contextValue = null;
    if (log.isDebugEnabled()) {

        log.debug("Following packages are in this batch of getJAXBContext() :");

        for (String pkg : contextPackages) {
            log.debug(pkg);
        }
        log.debug("This classloader will be used to construct the JAXBContext" + cl);
    }
    // The contextPackages is a set of package names that are constructed using PackageSetBuilder.
    // PackageSetBuilder gets the packages names from various sources.
    //   a) It walks the various annotations on the WebService collecting package names.
    //   b) It walks the wsdl/schemas and builds package names for each target namespace.
    //
    // The combination of these two sources should produce all of the package names.
    // -------------
    // Note that (b) is necessary for the following case:
    // An operation has a parameter named BASE.
    // Object DERIVED is an extension of BASE and is defined in a different package/schema.
    // In this case, there will not be any annotations on the WebService that reference DERIVED.
    // The only way to find the package for DERIVED is to walk the schemas.
    // -------------

    Iterator<String> it = contextPackages.iterator();
    while (it.hasNext()) {
        String p = it.next();
        // Don't consider java and javax packages
        // REVIEW: We might have to refine this
        if (p.startsWith("javax.xml.ws.wsaddressing")) {
            continue;
        }
        if (p.startsWith("java.") || p.startsWith("javax.")) {
            it.remove();
        }
    }

    // There are two ways to construct the context.
    // 1) USE A CONTEXTPATH, which is a string containing
    //    all of the packages separated by colons.
    // 2) USE A CLASS[], which is an array of all of the classes
    //    involved in the marshal/unmarshal.
    //
    // There are pros/cons with both approaches.
    // USE A CONTEXTPATH:
    //    Pros: preferred way of doing this.
    //          performant
    //          most dynamic
    //    Cons: Each package in context path must have an ObjectFactory
    //
    //
    // USE CLASS[]:
    //    Pros: Doesn't require ObjectFactory in each package
    //    Cons: Hard to set up, must account for JAX-WS classes, etc.
    //          Does not work if arrays of classes are needed
    //          slower
    //
    //  The following code attempts to build a context path.  It then
    //  choose one of the two constructions above (prefer USE A CONTEXT_PATH)
    //

    // The packages are examined to see if they have ObjectFactory/package-info classes.
    // Invalid packages are removed from the list
    it = contextPackages.iterator();
    boolean contextConstruction = (!forceArrays);
    boolean isJAXBFound = false;
    while (it.hasNext()) {
        String p = it.next();
        // See if this package has an ObjectFactory or package-info
        if (checkPackage(p, cl)) {
            // Flow to here indicates package can be used for CONTEXT construction
            isJAXBFound = true;
            if (log.isDebugEnabled()) {
                log.debug("Package " + p + " contains an ObjectFactory or package-info class.");
            }
        } else {
            // Flow to here indicates that the package is not valid for context construction.
            // Perhaps the package is invalid.
            if (log.isDebugEnabled()) {
                log.debug("Package " + p
                        + " does not contain an ObjectFactory or package-info class.  Searching for JAXB classes");
            }
            List<Class> classes = null;
            classes = getAllClassesFromPackage(p, cl);
            if (classes == null || classes.size() == 0) {
                if (log.isDebugEnabled()) {
                    log.debug("Package " + p
                            + " does not have any JAXB classes.  It is removed from the JAXB context path.");
                }
                it.remove();
            } else {
                // Classes are found in the package.  We cannot use the CONTEXT construction
                contextConstruction = false;
                if (log.isDebugEnabled()) {
                    log.debug("Package " + p
                            + " does not contain ObjectFactory, but it does contain other JAXB classes.");
                }
            }
        }
    }

    if (!isJAXBFound) {
        if (log.isDebugEnabled()) {
            log.debug("ObjectFactory & package-info are not found in package hierachy");
        }
    }

    // The code above may have removed some packages from the list.
    // Retry our lookup with the updated list
    if (contextConstruction) {
        if (log.isDebugEnabled()) {
            log.debug("Recheck Cache Start: Some packages have been removed from the list.  Rechecking cache.");
        }
        String key = contextPackages.toString();
        ConcurrentHashMap<ClassLoader, JAXBContextValue> innerMap = null;
        SoftReference<ConcurrentHashMap<ClassLoader, JAXBContextValue>> softRef = jaxbMap.get(key);
        if (softRef != null) {
            innerMap = softRef.get();
        }

        if (innerMap != null) {
            contextValue = innerMap.get(cl);
            if (forceArrays && contextValue != null
                    && contextValue.constructionType != JAXBUtils.CONSTRUCTION_TYPE.BY_CLASS_ARRAY_PLUS_ARRAYS) {
                if (log.isDebugEnabled()) {
                    log.debug("Found a JAXBContextValue with constructionType=" + contextValue.constructionType
                            + "  but the caller requested a JAXBContext "
                            + " that includes arrays.  A new JAXBContext will be built");
                }
                contextValue = null;
            }

            if (contextValue != null) {
                if (log.isDebugEnabled()) {
                    log.debug("Successfully found JAXBContext with updated context list:"
                            + contextValue.jaxbContext.toString());
                }
                return contextValue;
            }
        }
        if (log.isDebugEnabled()) {
            log.debug("Recheck Cache End: Did not find a JAXBContext.  Will build a new JAXBContext.");
        }
    }

    // CONTEXT construction
    if (contextConstruction) {
        if (log.isDebugEnabled()) {
            log.debug("Try building a JAXBContext using the packages only.");
        }
        JAXBContext context = createJAXBContextUsingContextPath(contextPackages, cl, classRefs);
        if (context != null) {
            contextValue = new JAXBContextValue(context, CONSTRUCTION_TYPE.BY_CONTEXT_PATH);
        }
        if (log.isDebugEnabled()) {
            log.debug("Building a JAXBContext with packages only success=" + (contextValue != null));
        }
    }

    // CLASS construction
    if (contextValue == null) {
        if (log.isDebugEnabled()) {
            log.debug("Try building a JAXBContext using a list of classes.");
            log.debug("Start finding classes");
        }
        it = contextPackages.iterator();
        List<Class> fullList = new ArrayList<Class>();
        while (it.hasNext()) {
            String pkg = it.next();
            fullList.addAll(getAllClassesFromPackage(pkg, cl));
        }
        //Lets add all common array classes
        addCommonArrayClasses(fullList);
        Class[] classArray = fullList.toArray(new Class[0]);
        if (log.isDebugEnabled()) {
            log.debug("End finding classes");
        }
        JAXBContext context = JAXBContext_newInstance(classArray, cl, properties, classRefs);
        if (context != null) {
            if (forceArrays) {
                contextValue = new JAXBContextValue(context, CONSTRUCTION_TYPE.BY_CLASS_ARRAY_PLUS_ARRAYS);
            } else {
                contextValue = new JAXBContextValue(context, CONSTRUCTION_TYPE.BY_CLASS_ARRAY);
            }
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Successfully created JAXBContext " + contextValue.jaxbContext.toString());
    }
    return contextValue;
}

From source file:org.apache.axis2.jaxws.message.databinding.JAXBUtils.java

/**
 * Create a JAXBContext using the contextPackages
 *
 * @param contextPackages Set<String>
 * @param cl              ClassLoader//from w  w w. j a  v  a2 s.co  m
 * @param forceArrays     boolean (true if JAXBContext must include all arrays)
 * @param properties      Map of properties for the JAXBContext.newInstance creation method
 * @param classRefs       List of class references
 * @return JAXBContextValue (JAXBContext + constructionType)
 * @throws JAXBException
 */
private static JAXBContextValue createJAXBContextValue(TreeSet<String> contextPackages, ClassLoader cl,
        boolean forceArrays, Map<String, ?> properties, List<String> classRefs) throws JAXBException {

    JAXBContextValue contextValue = null;
    if (log.isDebugEnabled()) {

        log.debug("Following packages are in this batch of getJAXBContext() :");

        for (String pkg : contextPackages) {
            log.debug(pkg);
        }
        log.debug("This classloader will be used to construct the JAXBContext" + cl);
    }
    // The contextPackages is a set of package names that are constructed using PackageSetBuilder.
    // PackageSetBuilder gets the packages names from various sources.
    //   a) It walks the various annotations on the WebService collecting package names.
    //   b) It walks the wsdl/schemas and builds package names for each target namespace.
    //
    // The combination of these two sources should produce all of the package names.
    // -------------
    // Note that (b) is necessary for the following case:
    // An operation has a parameter named BASE.
    // Object DERIVED is an extension of BASE and is defined in a different package/schema.
    // In this case, there will not be any annotations on the WebService that reference DERIVED.
    // The only way to find the package for DERIVED is to walk the schemas.
    // -------------

    Iterator<String> it = contextPackages.iterator();
    while (it.hasNext()) {
        String p = it.next();
        // Don't consider java and javax packages
        // REVIEW: We might have to refine this
        if (p.startsWith("javax.xml.ws.wsaddressing")) {
            continue;
        }
        if (p.startsWith("java.") || p.startsWith("javax.")) {
            it.remove();
        }
    }

    // There are two ways to construct the context.
    // 1) USE A CONTEXTPATH, which is a string containing
    //    all of the packages separated by colons.
    // 2) USE A CLASS[], which is an array of all of the classes
    //    involved in the marshal/unmarshal.
    //   
    // There are pros/cons with both approaches.
    // USE A CONTEXTPATH: 
    //    Pros: preferred way of doing this.  
    //          performant
    //          most dynamic
    //    Cons: Each package in context path must have an ObjectFactory
    //        
    //
    // USE CLASS[]:
    //    Pros: Doesn't require ObjectFactory in each package
    //    Cons: Hard to set up, must account for JAX-WS classes, etc.
    //          Does not work if arrays of classes are needed
    //          slower
    //
    //  The following code attempts to build a context path.  It then
    //  choose one of the two constructions above (prefer USE A CONTEXT_PATH)
    //

    // The packages are examined to see if they have ObjectFactory/package-info classes.
    // Invalid packages are removed from the list
    it = contextPackages.iterator();
    boolean contextConstruction = (!forceArrays);
    boolean isJAXBFound = false;
    while (it.hasNext()) {
        String p = it.next();
        // See if this package has an ObjectFactory or package-info
        if (checkPackage(p, cl)) {
            // Flow to here indicates package can be used for CONTEXT construction
            isJAXBFound = true;
            if (log.isDebugEnabled()) {
                log.debug("Package " + p + " contains an ObjectFactory or package-info class.");
            }
        } else {
            // Flow to here indicates that the package is not valid for context construction.
            // Perhaps the package is invalid.
            if (log.isDebugEnabled()) {
                log.debug("Package " + p
                        + " does not contain an ObjectFactory or package-info class.  Searching for JAXB classes");
            }
            List<Class> classes = null;
            classes = getAllClassesFromPackage(p, cl);
            if (classes == null || classes.size() == 0) {
                if (log.isDebugEnabled()) {
                    log.debug("Package " + p
                            + " does not have any JAXB classes.  It is removed from the JAXB context path.");
                }
                it.remove();
            } else {
                // Classes are found in the package.  We cannot use the CONTEXT construction
                contextConstruction = false;
                if (log.isDebugEnabled()) {
                    log.debug("Package " + p
                            + " does not contain ObjectFactory, but it does contain other JAXB classes.");
                }
            }
        }
    }

    if (!isJAXBFound) {
        if (log.isDebugEnabled()) {
            log.debug("ObjectFactory & package-info are not found in package hierachy");
        }
    }

    // The code above may have removed some packages from the list. 
    // Retry our lookup with the updated list
    if (contextConstruction) {
        if (log.isDebugEnabled()) {
            log.debug("Recheck Cache Start: Some packages have been removed from the list.  Rechecking cache.");
        }
        String key = contextPackages.toString();
        ConcurrentHashMap<ClassLoader, JAXBContextValue> innerMap = null;
        SoftReference<ConcurrentHashMap<ClassLoader, JAXBContextValue>> softRef = jaxbMap.get(key);
        if (softRef != null) {
            innerMap = softRef.get();
        }

        if (innerMap != null) {
            contextValue = innerMap.get(cl);
            if (forceArrays && contextValue != null
                    && contextValue.constructionType != JAXBUtils.CONSTRUCTION_TYPE.BY_CLASS_ARRAY_PLUS_ARRAYS) {
                if (log.isDebugEnabled()) {
                    log.debug("Found a JAXBContextValue with constructionType=" + contextValue.constructionType
                            + "  but the caller requested a JAXBContext "
                            + " that includes arrays.  A new JAXBContext will be built");
                }
                contextValue = null;
            }

            if (contextValue != null) {
                if (log.isDebugEnabled()) {
                    log.debug("Successfully found JAXBContext with updated context list:"
                            + contextValue.jaxbContext.toString());
                }
                return contextValue;
            }
        }
        if (log.isDebugEnabled()) {
            log.debug("Recheck Cache End: Did not find a JAXBContext.  Will build a new JAXBContext.");
        }
    }

    // CONTEXT construction
    if (contextConstruction) {
        if (log.isDebugEnabled()) {
            log.debug("Try building a JAXBContext using the packages only.");
        }
        JAXBContext context = createJAXBContextUsingContextPath(contextPackages, cl, classRefs);
        if (context != null) {
            contextValue = new JAXBContextValue(context, CONSTRUCTION_TYPE.BY_CONTEXT_PATH);
        }
        if (log.isDebugEnabled()) {
            log.debug("Building a JAXBContext with packages only success=" + (contextValue != null));
        }
    }

    // CLASS construction
    if (contextValue == null) {
        if (log.isDebugEnabled()) {
            log.debug("Try building a JAXBContext using a list of classes.");
            log.debug("Start finding classes");
        }
        it = contextPackages.iterator();
        List<Class> fullList = new ArrayList<Class>();
        while (it.hasNext()) {
            String pkg = it.next();
            fullList.addAll(getAllClassesFromPackage(pkg, cl));
        }
        //Lets add all common array classes
        addCommonArrayClasses(fullList);
        Class[] classArray = fullList.toArray(new Class[0]);
        if (log.isDebugEnabled()) {
            log.debug("End finding classes");
        }
        JAXBContext context = JAXBContext_newInstance(classArray, cl, properties, classRefs);
        if (context != null) {
            if (forceArrays) {
                contextValue = new JAXBContextValue(context, CONSTRUCTION_TYPE.BY_CLASS_ARRAY_PLUS_ARRAYS);
            } else {
                contextValue = new JAXBContextValue(context, CONSTRUCTION_TYPE.BY_CLASS_ARRAY);
            }
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Successfully created JAXBContext " + contextValue.jaxbContext.toString());
    }
    return contextValue;
}

From source file:com.mysql.stresstool.RunnableQueryDelete.java

public void run() {

    if (doDelete) {
        Connection conn = null;/*  w  w  w  .  j  av  a 2 s .  com*/

        try {
            if (jdbcUrlMap.get("dbType") != null && !((String) jdbcUrlMap.get("dbType")).equals("MySQL")) {
                conn = DriverManager.getConnection((String) jdbcUrlMap.get("dbType"), "test", "test");
            } else
                conn = DriverManager.getConnection((String) jdbcUrlMap.get("jdbcUrl"));
        } catch (SQLException ex) {
            ex.printStackTrace();
        }

        if (conn != null) {

            try {

                Statement stmt = null;
                ResultSet rs = null;

                conn.setAutoCommit(false);
                {
                    SoftReference sf = new SoftReference(conn.createStatement());
                    stmt = (Statement) sf.get();
                }

                //                      stmt2 = conn.createStatement();
                stmt.execute("SET AUTOCOMMIT=0");
                long execTime = 0;
                int pkStart = 0;
                int pkEnds = 0;
                ThreadInfo thInfo;

                long threadTimeStart = System.currentTimeMillis();
                active = true;

                thInfo = new ThreadInfo();
                thInfo.setId(this.ID);
                thInfo.setType("delete");
                thInfo.setStatusActive(this.isActive());

                StressTool.setInfoDelete(this.ID, thInfo);

                int deletedRows = 0;

                int[] pkStartAr = null;
                int[] pkEndsAr = null;
                String[][] sqlParameterValues;
                int[] iLine = { 0, 0 };

                //                      for(int repeat = 0 ; repeat < repeatNumber ; repeat++ ){
                //                      pkEndsAr[repeat] = StressTool.getNumberFromRandom(2147483647).intValue();
                //                      pkStartAr[repeat] = StressTool.getNumberFromRandom(pkEndsAr[repeat]- 10).intValue();
                //
                //                 }

                for (int repeat = 0; repeat < repeatNumber; repeat++) {
                    int maxDel = 0;
                    totalLineDeleted = 0;
                    //                         pkStart = pkStartAr[repeat];
                    //                          pkEnds = pkEndsAr[repeat];

                    //                              System.gc();

                    String deleteCheck1 = "";
                    long timeStart = System.currentTimeMillis();

                    try {
                        stmt.execute("BEGIN");

                        for (int iTable = 1; iTable <= this.getNumberOfprimaryTables(); iTable++) {
                            ResultSet rsToDelete = stmt
                                    .executeQuery("Select max(a),min(a) from tbtest" + iTable);
                            rsToDelete.next();
                            DecimalFormat df = new DecimalFormat("#.000000");
                            long maxDelete = rsToDelete.getLong(1);
                            long minDelete = rsToDelete.getLong(2);
                            long maxToDelete = new Double(
                                    ((double) this.getDeleterowmaxpct() * maxDelete) / 100).longValue();

                            PreparedStatement pstmt = null;
                            {
                                SoftReference sf = new SoftReference(conn.prepareStatement(
                                        "DELETE FROM tbtest" + iTable + " where a between  ? and ?"));
                                pstmt = (PreparedStatement) sf.get();
                            }

                            int deleted = 0;
                            if (maxDelete > 0) {

                                for (long iCdelete = minDelete; iCdelete < maxToDelete; iCdelete += getDeleterowsinterval()) {
                                    pstmt.setLong(1, iCdelete);
                                    pstmt.setLong(2, iCdelete += getDeleterowsinterval());
                                    int rows = pstmt.executeUpdate();
                                    if (rows > 0)
                                        deleted += rows;

                                    if (deleted >= maxToDelete) {
                                        totalLineDeleted += deleted;
                                        break;
                                    }
                                    stmt.execute("COMMIT");
                                }

                            }
                            stmt.execute("COMMIT");

                        }

                        if (!doSimplePk) {
                            for (int iTable = 1; iTable <= this.getNumberOfSecondaryTables(); iTable++) {
                                ResultSet rsToDelete = stmt
                                        .executeQuery("Select max(a),min(a) from tbtest_child" + iTable);
                                rsToDelete.next();
                                DecimalFormat df = new DecimalFormat("#.000000");
                                long maxDelete = rsToDelete.getLong(1);
                                long minDelete = rsToDelete.getLong(2);
                                long maxToDelete = new Double(
                                        ((double) this.getDeleterowmaxpct() * maxDelete) / 100).longValue();

                                PreparedStatement pstmt = conn.prepareStatement(
                                        "DELETE FROM tbtest_child" + iTable + " where a between  ? and ?");
                                int deleted = 0;
                                if (maxDelete > 0) {

                                    for (long iCdelete = minDelete; iCdelete < maxToDelete; iCdelete += getDeleterowsinterval()) {
                                        pstmt.setLong(1, iCdelete);
                                        pstmt.setLong(2, iCdelete += getDeleterowsinterval());
                                        int rows = pstmt.executeUpdate();
                                        if (rows > 0)
                                            deleted += rows;

                                        if (deleted >= maxToDelete) {
                                            totalLineDeleted += deleted;
                                            break;
                                        }
                                        stmt.execute("COMMIT");
                                    }

                                }
                                stmt.execute("COMMIT");
                            }
                        }

                        long timeEnds = System.currentTimeMillis();
                        execTime = (timeEnds - timeStart);

                    } catch (SQLException sqle) {
                        conn.rollback();
                        //                                  System.out.println("Query Delete1 = " + deleteCheck1);
                        /** 
                         Silently skip any deadlock
                        **/
                        if (StressTool.getErrorLogHandler() != null) {
                            StressTool.getErrorLogHandler().appendToFile(sqle.toString());
                        }

                        //                                  sqle.printStackTrace();
                    } finally {

                    }

                    if (doLog) {
                        System.out.println("Query Delete TH = " + this.getID() + " Id = " + pkStart
                                + " IdEnd = " + pkEnds + " " + "Deleted lines " + (totalLineDeleted)
                                + " Exec Time(ms) =" + execTime);
                    }

                    thInfo.setExecutedLoops(repeat);
                    Thread.sleep(sleepFor);
                }

                stmt.close();
                //                      stmt2.close();
                conn.close();

                long threadTimeEnd = System.currentTimeMillis();
                this.executionTime = (threadTimeEnd - threadTimeStart);
                this.setExecutionTime(executionTime);
                active = false;
                //                      System.out.println("Query Delete TH = " + this.getID() +" Id = " + pkStart + 
                //                            " IdEnd = " + pkEnds + " " + "Deleted lines " +
                //                              deletedRows + " Exec Time(ms) =" + execTime + " Sec =" + (execTime/1000));

                thInfo.setExecutionTime(executionTime);
                thInfo.setStatusActive(false);
                StressTool.setInfoDelete(this.ID, thInfo);
                return;

            } catch (Exception ex) {
                ex.printStackTrace();
            }

        }

    }
}

From source file:de.fhg.igd.mapviewer.AbstractTileOverlayPainter.java

private BufferedImage getCachedTile(int x, int y, int zoom) {
    BufferedImage result = null;//from w  ww . ja  v  a  2s .  c o  m

    synchronized (cache) {
        // cache per zoom
        final TIntObjectHashMap<TIntObjectHashMap<SoftReference<BufferedImage>>> zoomCache = cache.get(zoom);

        if (zoomCache != null) {
            // cache per x
            final TIntObjectHashMap<SoftReference<BufferedImage>> xCache = zoomCache.get(x);
            if (xCache != null) {
                // img cache
                final SoftReference<BufferedImage> imgCache = xCache.get(y);
                if (imgCache != null) {
                    result = imgCache.get();
                }
            }
        }
    }

    return result;
}

From source file:jetbrains.exodus.env.EnvironmentImpl.java

@Nullable
LongObjectCacheBase getTreeNodesCache() {
    final SoftReference<LongObjectCacheBase> cacheRef = treeNodesCache;
    if (cacheRef != null) {
        final LongObjectCacheBase cache = cacheRef.get();
        return cache != null ? cache : invalidateTreeNodesCache();
    }//w w w .  j a va 2 s .  c om
    return null;
}

From source file:com.amalto.commons.core.utils.xpath.ri.JXPathContextReferenceImpl.java

/**
 * Compile the given expression./*from  w w w. j a v  a2 s  . c  o  m*/
 * @param xpath to compile
 * @return Expression
 */
private Expression compileExpression(String xpath) {
    Expression expr;

    synchronized (compiled) {
        if (USE_SOFT_CACHE) {
            expr = null;
            SoftReference ref = (SoftReference) compiled.get(xpath);
            if (ref != null) {
                expr = (Expression) ref.get();
            }
        } else {
            expr = (Expression) compiled.get(xpath);
        }
    }

    if (expr != null) {
        return expr;
    }

    expr = (Expression) Parser.parseExpression(xpath, getCompiler());

    synchronized (compiled) {
        if (USE_SOFT_CACHE) {
            if (cleanupCount++ >= CLEANUP_THRESHOLD) {
                Iterator it = compiled.entrySet().iterator();
                while (it.hasNext()) {
                    Entry me = (Entry) it.next();
                    if (((SoftReference) me.getValue()).get() == null) {
                        it.remove();
                    }
                }
                cleanupCount = 0;
            }
            compiled.put(xpath, new SoftReference(expr));
        } else {
            compiled.put(xpath, expr);
        }
    }

    return expr;
}

From source file:com.geeker.door.imgcache.ImageDownloader.java

/**
 * @param url/* ww  w . j av  a  2  s  .  c om*/
 *            The URL of the image that will be retrieved from the cache.
 * @return The cached bitmap or null if it was not found.
 */
public Bitmap getBitmapFromCache(String url) {
    if (url == null || url.length() == 0)
        return null;
    // First try the hard reference cache
    synchronized (mHardBitmapCache) {
        final Bitmap bitmap = mHardBitmapCache.get(url);
        if (bitmap != null) {
            // Bitmap found in hard cache
            // Move element to first position, so that it is removed last
            mHardBitmapCache.remove(url);
            mHardBitmapCache.put(url, bitmap);
            // Logger.d(
            // "ImageDownloader",
            // "RAM HardReference Cache==>" + "Heap:"
            // + (Debug.getNativeHeapSize() / 1024) + "KB "
            // + "FreeHeap:"
            // + (Debug.getNativeHeapFreeSize() / 1024)
            // + "KB " + "AllHeap:"
            // + (Debug.getNativeHeapAllocatedSize() / 1024)
            // + "KB" + " url:" + url);
            return bitmap;
        }
    }

    // Then try the soft reference cache
    SoftReference<Bitmap> bitmapReference = mSoftBitmapCache.get(url);
    if (bitmapReference != null) {
        final Bitmap bitmap = bitmapReference.get();
        if (bitmap != null) {
            // Bitmap found in soft cache
            // Logger.d(
            // "ImageDownloader",
            // "RAM SoftReference Cache==>" + "Heap:"
            // + (Debug.getNativeHeapSize() / 1024) + "KB "
            // + "FreeHeap:"
            // + (Debug.getNativeHeapFreeSize() / 1024)
            // + "KB " + "AllHeap:"
            // + (Debug.getNativeHeapAllocatedSize() / 1024)
            // + "KB" + " url:" + url);
            return bitmap;
        } else {
            // Soft reference has been Garbage Collected
            mSoftBitmapCache.remove(url);
        }
    }

    return null;
}

From source file:net.sourceforge.fenixedu.domain.Degree.java

public static Degree readBySigla(final String sigla) {
    if (degrees.isEmpty()) {
        loadCache();// ww w  .  j  a  v a 2s  .com
    }
    final String lowerCaseString = sigla.toLowerCase();
    final SoftReference<Degree> degreeReference = degrees.get(lowerCaseString);
    if (degreeReference != null) {
        final Degree degree = degreeReference.get();
        if (degree != null && degree.getRootDomainObject() == Bennu.getInstance()
                && degree.getSigla().equalsIgnoreCase(lowerCaseString)) {
            return degree;
        } else {
            loadCache();
            final SoftReference<Degree> otherDegreeReference = degrees.get(lowerCaseString);
            if (otherDegreeReference != null) {
                final Degree otherDegree = otherDegreeReference.get();
                if (otherDegree != null && otherDegree.getRootDomainObject() == Bennu.getInstance()
                        && otherDegree.getSigla().equalsIgnoreCase(lowerCaseString)) {
                    return otherDegree;
                }
            }
        }
    }

    return null;
}

From source file:com.corebase.android.bitmap.util.ImageCache.java

/**
 * @param options//from www .j  ava2 s .c  o  m
 *            - BitmapFactory.Options with out* options populated
 * @return Bitmap that case be used for inBitmap
 */
// private final Object mIteratorLock = new Object();
protected Bitmap getBitmapFromReusableSet(BitmapFactory.Options options) {
    Bitmap bitmap = null;
    if (mReusableBitmaps != null && !mReusableBitmaps.isEmpty()) {
        // final Iterator<SoftReference<Bitmap>> iterator =
        // mReusableBitmaps.iterator();
        Bitmap item;
        SoftReference<Bitmap> reference = null;
        for (String key : mReusableBitmaps.keySet()) {
            reference = mReusableBitmaps.get(key);
            if (reference != null) {
                item = reference.get();
                if (null != item && item.isMutable()) {
                    if (canUseForInBitmap(item, options)) {
                        bitmap = item;
                        mReusableBitmaps.remove(key);
                    }
                } else {
                    mReusableBitmaps.remove(key);
                }
            }
        }

        // while (iterator.hasNext()) {
        // reference = iterator.next();
        // item = reference.get();
        // if (null != item && item.isMutable()) {
        // // Check to see it the item can be used for inBitmap
        // if (canUseForInBitmap(item, options)) {
        // bitmap = item;
        // // Remove from reusable set so it can't be used again
        // iterator.remove();
        // if(mReusableBitmaps.contains(reference)){
        // mReusableBitmaps.remove(reference);
        // }
        // break;
        // }
        // } else {
        // // Remove from the set if the reference has been cleared.
        // iterator.remove();
        // if(mReusableBitmaps.contains(reference)){
        // mReusableBitmaps.remove(reference);
        // }
        // }
        // }
    }
    return bitmap;
}

From source file:com.mysql.stresstool.RunnableQuerySelectPCH.java

/**
 * When an object implementing interface <code>Runnable</code> is used to create a thread, starting the thread causes the object's <code>run</code> method to be called in
 * that separately executing thread.//  w w  w.j  a  v a  2  s  .  c o m
 *
 * @todo Implement this java.lang.Runnable method
 */
public void run() {

    Connection conn = createConnection();
    {
        SoftReference sf = new SoftReference(createConnection());
        conn = (Connection) sf.get();
    }

    if (conn != null) {
        ThreadInfo thInfo;
        thInfo = new ThreadInfo();
        thInfo.setId(this.ID);
        thInfo.setType("select");
        active = true;
        thInfo.setStatusActive(this.isActive());
        StressTool.setInfoSelect(this.ID, thInfo);

        try {
            Statement stmt = null;
            ResultSet rs = null;
            conn.setAutoCommit(false);
            stmt = conn.createStatement();
            PreparedStatement pstmt;
            long execTime = 0;
            int repeat = 0;
            int sqlParameterNumbers = 0;

            long threadTimeStart = System.currentTimeMillis();

            if (this.sqlQuery != null && !this.sqlQuery.equals("")) {
                try {

                    pstmt = conn.prepareStatement(sqlQuery);
                    sqlParameterNumbers = pstmt.getParameterMetaData().getParameterCount();

                } catch (SQLException sqlex) {
                    sqlex.printStackTrace();
                    conn.close();
                    return;
                }
            } else {
                pstmt = null;
            }

            String[][] sqlParameterValues;

            if (this.sqlQuery == null || this.sqlQuery.equals("")) {
                pkRange = new PrimaryKeyRangeDefiner(repeatNumber);
                pkRange.setLastResetLoop(0);
                pkRange = setPkRange(conn, pkRange);

                //                              3351000110
                sqlParameterValues = null;
            } else {
                sqlParameterValues = new String[repeatNumber][sqlParameterNumbers];
                for (repeat = 0; repeat < repeatNumber; repeat++) {
                    for (int pvalue = 0; pvalue < sqlParameterNumbers; pvalue++) {
                        sqlParameterValues[repeat][pvalue] = "3"
                                + String.valueOf(StressTool.getNumberFromRandom(500000000).intValue());
                    }
                }

            }

            for (repeat = 0; repeat < repeatNumber; repeat++) {
                int pkStart = 0;
                int pkEnds = 0;
                int recordFound = 0;
                if (repeat > 0 && pkRange.getLooprefresh() < (repeat - pkRange.getLastResetLoop())) {
                    pkRange = setPkRange(conn, pkRange);
                    pkRange.setLastResetLoop(repeat);
                }

                if (pkRange.getKeyStart(repeat) > 0 && pkRange.getKeyEnd(repeat) > 0) {
                    pkStart = pkRange.getKeyStart(repeat);
                    pkEnds = pkRange.getKeyEnd(repeat);
                }

                if (pkStart > pkEnds) {
                    int dummy = pkStart;
                    pkStart = pkEnds;
                    pkEnds = dummy;
                }

                if (pkEnds == 0)
                    continue;

                String select = "";
                {
                    SoftReference sf = new SoftReference(generateSelectString(pkStart, pkEnds, select));
                    select = (String) sf.get();
                }
                int[] iLine = null;

                try {

                    long timeStart = System.currentTimeMillis();

                    try {
                        if (this.sqlQuery != null && !this.sqlQuery.equals("")) {

                            if (this.getIBatchSelect() > 0) {
                                for (int pstmtbatch = 0; pstmtbatch < this.getIBatchSelect(); pstmtbatch++) {
                                    for (int ii = 1; ii <= sqlParameterNumbers; ii++) {
                                        pstmt.setString(ii, sqlParameterValues[StressTool
                                                .getNumberFromRandom(repeatNumber).intValue()][ii - 1]);
                                        {
                                            SoftReference sf = new SoftReference(pstmt.executeQuery());
                                            rs = (ResultSet) sf.get();
                                        }

                                        //                                             System.out.print(this.sqlQuery + " BATCH | " + ii +" | " + sqlParameterValues[repeat][ii - 1] + "\n") ;
                                    }
                                }
                            } else {
                                for (int ii = 1; ii <= sqlParameterNumbers; ii++) {
                                    pstmt.setString(ii, sqlParameterValues[repeat][ii - 1]);
                                    //                                        System.out.print(this.sqlQuery + " | " + ii +" | " + sqlParameterValues[repeat][ii - 1] + "\n") ;
                                }
                                rs = pstmt.executeQuery();

                            }

                        } else {
                            rs = stmt.executeQuery(select);
                            rs.last();
                        }
                    } catch (Exception ex) {
                        if (StressTool.getErrorLogHandler() != null) {
                            StressTool.getErrorLogHandler().appendToFile(ex.toString());
                        } else
                            ex.printStackTrace();
                    } finally {
                        if (rs != null) {
                            rs.close();
                            rs = null;
                        }

                    }
                    long timeEnds = System.currentTimeMillis();
                    //                            recordFound = rs.getRow();

                    execTime = (timeEnds - timeStart);
                    thInfo.setExecutedLoops(repeat);

                } catch (SQLException sqle) {
                    if (StressTool.getErrorLogHandler() != null) {
                        StressTool.getErrorLogHandler().appendToFile(sqle.toString());
                    } else
                        sqle.printStackTrace();
                } finally {
                    if (rs != null) {
                        rs.close();
                        rs = null;
                    }

                    //                            intDeleteInterval++;
                    if (doLog)
                        System.out.println(
                                "Query Select TH = " + this.getID() + " Id = " + pkStart + " IdEnd = " + pkEnds
                                        + " Record found = " + recordFound + " Exec Time(ms) =" + execTime);

                }

                if (sleepFor > 0 || this.getSleepSelect() > 0) {
                    if (this.getSleepSelect() > 0) {
                        Thread.sleep(getSleepSelect());
                    } else
                        Thread.sleep(sleepFor);
                }
            }
            //                System.out.println("Query Select/Delete TH = " + this.getID() + " COMPLETED! ");

            long threadTimeEnd = System.currentTimeMillis();
            this.executionTime = (threadTimeEnd - threadTimeStart);
            //                this.setExecutionTime(executionTime);

            active = false;
            thInfo.setExecutionTime(executionTime);
            thInfo.setStatusActive(false);
            StressTool.setInfoSelect(this.ID, thInfo);
            stmt = null;

            return;

        } catch (Exception ex) {
            ex.printStackTrace();
            try {
                conn.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

}