Example usage for java.lang.ref SoftReference SoftReference

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

Introduction

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

Prototype

public SoftReference(T referent) 

Source Link

Document

Creates a new soft reference that refers to the given object.

Usage

From source file:com.guang.eunormia.common.cache.DefaultLocalCache.java

@Override
public V put(K key, V value, int TTL) {
    SoftReference<V> result = getCache(key).put(key, new SoftReference<V>(value));

    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.SECOND, TTL);
    expiryCache.put(key, calendar.getTime().getTime());

    return result == null ? null : result.get();
}

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

public void run() {

    BufferedReader d = null;/*from  w  ww. j a  v a2 s .c  om*/
    Connection conn = null;

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

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

    try {

        long execTime = 0;
        int pkStart = 0;
        int pkEnds = 0;
        int intDeleteInterval = 0;
        int intBlobInterval = 0;
        int intBlobIntervalLimit = StressTool.getNumberFromRandom(4).intValue();
        ThreadInfo thInfo;

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

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

        StressTool.setInfo(this.ID, thInfo);
        boolean lazy = false;
        int lazyInterval = 0;

        for (int repeat = 0; repeat <= repeatNumber; repeat++) {
            if (!stikyconnection) {
                try {
                    if (conn != null && !conn.isClosed()) {
                        conn.close();
                    }
                    SoftReference sf = new SoftReference(
                            DriverManager.getConnection((String) jdbcUrlMap.get("jdbcUrl")));
                    conn = (Connection) sf.get();
                } catch (SQLException ex) {
                    for (int icon = 0; icon <= 3; icon++) {
                        try {
                            Thread.sleep(10000);
                            SoftReference sf = new SoftReference(
                                    DriverManager.getConnection((String) jdbcUrlMap.get("jdbcUrl")));
                            conn = (Connection) sf.get();
                        } catch (SQLException ex2) {
                            ex2.printStackTrace();
                        }
                    }
                    //ex.printStackTrace();
                }

            }
            if (conn != null) {
                Statement stmt = null;
                //                ResultSet rs = null;
                //                ResultSet rs2 = null;

                conn.setAutoCommit(false);
                stmt = conn.createStatement();
                stmt.execute("SET AUTOCOMMIT=0");

                String query = null;
                ArrayList insert1 = null;
                ArrayList insert2 = null;
                int pk = 0;

                if (repeat > 0 && lazyInterval < 500) {
                    lazy = true;
                    ++lazyInterval;
                } else {
                    lazy = false;
                    lazyInterval = 0;
                }

                intBlobInterval++;
                //IMPLEMENTING lazy
                Vector v = this.getTablesValues(lazy);

                insert1 = (ArrayList<String>) v.get(0);
                insert2 = (ArrayList<String>) v.get(1);

                //                    System.out.println(insert1);
                //                    System.out.println(insert2);

                //                    pk = ((Integer) v.get(2)).intValue();

                int[] iLine = { 0, 0 };

                //                    pkStart = StressTool.getNumberFromRandom(2147483647).intValue();
                //                    pkEnds = StressTool.getNumberFromRandom(2147483647).intValue();

                try {

                    long timeStart = System.currentTimeMillis();

                    if (this.ignoreBinlog)
                        stmt.execute("SET sql_log_bin=0");
                    //stmt.execute("SET GLOBAL max_allowed_packet=1073741824");

                    if (dbType.equals("MySQL") && !engine.toUpperCase().equals("BRIGHTHOUSE"))
                        stmt.execute("BEGIN");
                    else
                        stmt.execute("COMMIT");
                    //                                stmt.execute("SET TRANSACTION NAME 'TEST'");
                    {
                        Iterator<String> it = insert1.iterator();
                        while (it.hasNext()) {
                            stmt.addBatch(it.next());
                        }
                    }

                    if (!this.doSimplePk) {
                        if (intBlobInterval > intBlobIntervalLimit) {
                            Iterator<String> it = insert2.iterator();
                            while (it.hasNext()) {
                                stmt.addBatch(it.next());
                            }
                            intBlobInterval = 0;

                        }
                    }
                    if (debug) {
                        System.out.println("Thread " + thInfo.getId() + " Executing loop "
                                + thInfo.getExecutedLoops() + " QUERY1==" + insert1);
                        System.out.println("Thread " + thInfo.getId() + " Executing loop "
                                + thInfo.getExecutedLoops() + " QUERY2==" + insert2);

                    }

                    iLine = executeSQL(stmt);
                    //                            System.out.println("Query1 = " + insert1);
                    //                            System.out.println("Query2 = " + insert2);
                    //                            stmt.execute("START TRANSACTION");
                    //                            stmt.execute(insert1);
                    //                            iLine = stmt.executeBatch();
                    //                            conn.commit();
                    long timeEnds = System.currentTimeMillis();
                    execTime = (timeEnds - timeStart);

                } catch (SQLException sqle) {

                    conn.rollback();
                    System.out.println("FAILED QUERY1==" + insert1);
                    System.out.println("FAILED QUERY2==" + insert2);
                    sqle.printStackTrace();
                    System.exit(1);
                    //conn.close();
                    //this.setJdbcUrl(jdbcUrl);
                    //System.out.println("Query Insert TH RE-INIZIALIZING");

                } finally {
                    //                           conn.commit();
                    if (conn != null && !conn.isClosed()) {
                        try {
                            stmt.addBatch("COMMIT");
                            executeSQL(stmt);
                        } catch (SQLException sqle) {
                            System.out.println(
                                    "#####################\n[Warning] Cannot explicitly commit given error\n#################");
                            conn.close();
                            continue;
                        }
                    } else {
                        System.out.println(
                                "#####################\n[Warning] Cannot explicitly commit given connection was interrupted unexpectedly\n#################");
                    }
                    //                            intDeleteInterval++;
                    if (doLog) {

                        System.out.println("Query Insert TH = " + this.getID() + " Loop N = " + repeat + " "
                                + iLine[0] + "|" + ((iLine.length > 1) ? iLine[1] : 0) + " Exec Time(ms) ="
                                + execTime + " Running = " + repeat + " of " + repeatNumber + " to go ="
                                + (repeatNumber - repeat) + " Using Lazy=" + lazy);
                    }
                }
                thInfo.setExecutedLoops(repeat);
                if (sleepFor > 0 || this.getSleepWrite() > 0) {
                    if (this.getSleepWrite() > 0) {
                        Thread.sleep(getSleepWrite());
                    } else
                        Thread.sleep(sleepFor);
                }

            }
        }

        long threadTimeEnd = System.currentTimeMillis();
        this.executionTime = (threadTimeEnd - threadTimeStart);
        //                this.setExecutionTime(executionTime);
        active = false;
        //                System.out.println("Query Insert TH = " + this.getID() + " COMPLETED!  TOTAL TIME = " + execTime + "(ms) Sec =" + (execTime/1000));

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

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

}

From source file:net.sf.jasperreports.engine.util.JRStyledTextParser.java

/**
 * Return a cached instance.//from w ww  . j  a v a 2 s  .c om
 * 
 * @return a cached instance
 */
public static JRStyledTextParser getInstance() {
    JRStyledTextParser instance = null;
    SoftReference<JRStyledTextParser> instanceRef = threadInstances.get();
    if (instanceRef != null) {
        instance = instanceRef.get();
    }
    if (instance == null) {
        instance = new JRStyledTextParser();
        threadInstances.set(new SoftReference<JRStyledTextParser>(instance));
    }
    return instance;
}

From source file:com.cm.beer.util.DrawableManager.java

/**
 * //from ww w  .j  av a2  s .co  m
 * @param urlString
 * @return
 */
public byte[] fetchDrawableAsByteArray(String urlString) {
    byte[] bitmapdata = null;

    if (mDrawableCache.containsKey(urlString)) {
        if (Logger.isLogEnabled())
            Logger.log("Returning Drawable from Cache:" + urlString);
        SoftReference<Drawable> softReference = mDrawableCache.get(urlString);
        if ((softReference == null) || (softReference.get() == null)) {
            mDrawableCache.remove(urlString);
            if (Logger.isLogEnabled())
                Logger.log("fetchDrawable():Soft Reference has been Garbage Collected:" + urlString);
        } else {
            Drawable drawable = softReference.get();
            Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
            bitmapdata = stream.toByteArray();
        }
    }

    if (Logger.isLogEnabled())
        Logger.log("image url:" + urlString);
    try {
        // prevents multithreaded fetches for the same image
        mLockCache.put(urlString, urlString);
        if (Logger.isLogEnabled())
            Logger.log("Begin Downloading:" + urlString);
        InputStream is = fetch(urlString);
        if (Logger.isLogEnabled())
            Logger.log("End Downloading:" + urlString);
        Drawable drawable = Drawable.createFromStream(is, "src");
        mDrawableCache.put(urlString, new SoftReference<Drawable>(drawable));
        mLockCache.remove(urlString);
        if (Logger.isLogEnabled())
            Logger.log("got a thumbnail drawable: " + drawable.getBounds() + ", "
                    + drawable.getIntrinsicHeight() + "," + drawable.getIntrinsicWidth() + ", "
                    + drawable.getMinimumHeight() + "," + drawable.getMinimumWidth());

        Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        bitmapdata = stream.toByteArray();

    } catch (Throwable e) {
        Log.e(this.getClass().getName(), "fetchDrawable failed", e);
        return null;
    }
    return bitmapdata;
}

From source file:com.slytechs.capture.file.AbstractFile.java

/**
 * Caches an indexer and creates a new instance if one is not cached.
 * /*from w  ww . ja  va  2  s .  c om*/
 * @return position indexer for all records
 * @throws IOException
 *           any IO errors
 */
public PositionIndexer getPositionIndexer() throws IOException {
    if (this.indexer == null || this.indexer.get() == null) {
        this.indexer = new SoftReference<PositionIndexer>(
                new RecordPositionIndexer(this.editor.getFlexRegion()));
    }

    return this.indexer.get();
}

From source file:org.polymap.core.data.operations.feature.BufferFeaturesOperation.java

/**
 * // w  w w .  j ava  2  s  . c  o m
 */
@Override
public Status execute(IProgressMonitor monitor) throws Exception {
    monitor.beginTask(context.adapt(FeatureOperationExtension.class).getLabel(), 100);

    final PipelineFeatureSource fs = (PipelineFeatureSource) context.featureSource();

    // wizard dialog
    monitor.subTask(i18n("userInput"));
    IUndoableOperation op = context.adapt(IUndoableOperation.class);
    OperationWizard wizard = new OperationWizard(op, context, monitor) {
        public boolean doPerformFinish() throws Exception {
            return true;
        }
    };
    final BufferInputPage bufferInputPage = new BufferInputPage();
    wizard.addPage(bufferInputPage);

    monitor.worked(10);

    // open wizard dialog
    if (OperationWizard.openDialog(wizard)) {
        monitor.worked(10);
        final IProgressMonitor submon = new SubProgressMonitor(monitor, 80,
                SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK);

        FeatureCollection features = context.features();
        CoordinateReferenceSystem crs = context.featureSource().getSchema().getCoordinateReferenceSystem();
        crs = crs != null ? crs : layer.getMap().getCRS();
        final Unit<?> uom = crs.getCoordinateSystem().getAxis(0).getUnit();

        int featuresSize = features.size();
        submon.beginTask(i18n("submonTitle", featuresSize), featuresSize);

        final HashMap<FeatureId, Geometry> undoMap = new HashMap<FeatureId, Geometry>();

        Transaction tx = new DefaultTransaction("BufferFeaturesOperation");
        fs.setTransaction(tx);

        FeatureIterator it = features.features();
        try {
            for (int count = 0; it.hasNext() && !submon.isCanceled(); count++) {
                if (count % 100 == 0) {
                    submon.worked(100);
                    submon.subTask(String.valueOf(count));
                }
                Feature feature = it.next();
                Geometry geom = (Geometry) feature.getDefaultGeometryProperty().getValue();
                GeometryDescriptor geomDesc = feature.getDefaultGeometryProperty().getDescriptor();

                undoMap.put(feature.getIdentifier(), geom);

                if (uom.toString().equalsIgnoreCase("m")) {
                    geom = geom.buffer(bufferInputPage.distance, bufferInputPage.segments);
                } else {
                    geom = Geometries.transform(geom, crs, Geometries.crs("EPSG:3857"));
                    geom = geom.buffer(bufferInputPage.distance, bufferInputPage.segments);
                    geom = Geometries.transform(geom, Geometries.crs("EPSG:3857"), crs);
                }
                fs.modifyFeatures(geomDesc, geom, ff.id(Collections.singleton(feature.getIdentifier())));
            }
            undo = new SoftReference(undoMap);
            tx.commit();
        } catch (Exception e) {
            tx.rollback();
            throw new RuntimeException(e);
        } finally {
            tx.close();
            it.close();
            submon.done();
        }

        monitor.done();
        return Status.OK;
    }
    return Status.Cancel;
}

From source file:com.eviware.soapui.security.log.SecurityTestLogModel.java

public synchronized void addSecurityScanResult(SecurityScan securityCheck) {
    int size = items.size();
    checkCount++;//w  w  w .  jav  a 2  s . c  om
    requestCount = 0;

    SecurityScanResult securityCheckResult = securityCheck.getSecurityScanResult();
    SoftReference<SecurityResult> checkResultRef = new SoftReference<SecurityResult>(securityCheckResult);

    items.add("SecurityScan " + checkCount + " [" + securityCheck.getName() + "] ");
    results.add(checkResultRef);
    currentCheckEntriesCount = 1;
    currentStepEntriesCount++;

    fireIntervalAdded(this, size, items.size() - 1);
    enforceMaxSize();
}

From source file:com.rsegismont.androlife.common.utils.ImageCacher.java

/**
 * Initialize the cache, providing all parameters.
 * //from   w  ww  . ja  v  a 2s. c om
 * @param cacheParams
 *            The cache parameters to initialize the cache
 */
@SuppressLint("UseSparseArrays")
private void init(ImageCacheParams cacheParams) {
    mCacheParams = cacheParams;

    // Set up memory cache
    if (mCacheParams.memoryCacheEnabled) {
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "Memory cache created (size = " + mCacheParams.memCacheSize + ")");
        }

        // If we're running on Honeycomb or newer, then
        if (Utils.hasHoneycomb()) {
            mReusableBitmaps = new ConcurrentSkipListMap<Integer, SoftReference<Bitmap>>();
        }

        mMemoryCacheSize = new HashMap<String, Point>();

        mMemoryCacheData = new LruCache<String, BitmapDrawable>(mCacheParams.memCacheSize) {

            /**
             * Notify the removed entry that is no longer being cached
             */
            @Override
            protected void entryRemoved(boolean evicted, String key, BitmapDrawable oldValue,
                    BitmapDrawable newValue) {
                if (RecyclingBitmapDrawable.class.isInstance(oldValue)) {
                    // The removed entry is a recycling drawable, so notify
                    // it
                    // that it has been removed from the memory cache
                    ((RecyclingBitmapDrawable) oldValue).setIsCached(false);
                } else {
                    // The removed entry is a standard BitmapDrawable

                    if (Utils.hasHoneycomb()) {
                        // We're running on Honeycomb or later, so add the
                        // bitmap
                        // to a SoftRefrence set for possible use with
                        // inBitmap later

                        synchronized (mMemCacheLock) {
                            if (evicted == true) {
                                mReusableBitmaps.put(getBitmapSize(oldValue),
                                        new SoftReference<Bitmap>(oldValue.getBitmap()));
                            }
                        }
                    }
                }
            }

            /**
             * Measure item size in kilobytes rather than units which is
             * more practical for a bitmap cache
             */
            @Override
            protected int sizeOf(String key, BitmapDrawable value) {
                final int bitmapSize = getBitmapSize(value) / 1024;
                return bitmapSize == 0 ? 1 : bitmapSize;
            }
        };
    }

    // By default the disk cache is not initialized here as it should be
    // initialized
    // on a separate thread due to disk access.
    if (cacheParams.initDiskCacheOnCreate) {
        // Set up disk cache
        initDiskCache();
    }
}

From source file:com.cloverstudio.spika.utils.BitmapManager.java

private Bitmap downloadBitmap(String url) {
    try {//from w w w.ja  v a 2 s  .  c o m
        Bitmap bitmap = BitmapFactory.decodeStream(
                (InputStream) ConnectionHandler.httpGetRequest(url, UsersManagement.getLoginUser().getId()));
        imgRatio = (float) bitmap.getWidth() / (float) bitmap.getHeight();
        smallImg = false;

        //         int REQUIRED_SIZE = 100;
        //
        //         int width = 0;
        //         int height = 0;
        //
        //         if (bitmap.getHeight() < REQUIRED_SIZE
        //               && bitmap.getWidth() < REQUIRED_SIZE) {
        //            width = bitmap.getWidth();
        //            height = bitmap.getHeight();
        //            smallImg = true;
        //         } else if (bitmap.getHeight() < height) {
        //            height = bitmap.getHeight();
        //         } else if (bitmap.getWidth() < width) {
        //            width = bitmap.getWidth();
        //         }
        //
        //
        //         bitmap = Bitmap.createScaledBitmap(bitmap,
        //               (int) (height * imgRatio), height, true);
        cache.put(url, new SoftReference<Bitmap>(bitmap));
        return bitmap;
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (SpikaException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SpikaForbiddenException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return null;
}

From source file:FastCache.java

void setFirstRecord(int bucketId, Record<K, V> record) {
    SoftReference<Record<K, V>> ref = new SoftReference<Record<K, V>>(record);
    mBuckets[bucketId] = ref;//from ww w.j  a  v a 2s.  co m
}