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.daveayan.rjson.Rjson.java

public String toJson(Object object) {
    log.debug("Converting to json " + object);
    if (object instanceof String) {
        return object.toString();
    }// w ww . jav  a 2 s.c o  m
    StringBufferPrinter json_buffer = new StringBufferPrinter();
    Context context = Context.newInstance().put("rjson", this).and("json_buffer", json_buffer).and("cycle_set",
            new SoftReference<Set<?>>(new HashSet<Object>()));
    object_to_json_transformer.transform(object, String.class, "", context);
    log.debug("json before formatting is : " + json_buffer.toString());
    String json = json_buffer.toString();
    if (formatJson()) {
        json = RjsonUtil.reformat(json_buffer.toString());
    }
    log.debug("json is : " + json);
    return json;
}

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

public void run() {

    if (doDelete) {
        Connection conn = null;//from  ww w .ja  v a 2s .c o  m

        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:com.example.com.jglx.android.app.util.video.ImageCache.java

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

    // BEGIN_INCLUDE(init_memory_cache)
    // Set up memory cache
    if (mCacheParams.memoryCacheEnabled) {

        if (Utils.hasHoneycomb()) {
            mReusableBitmaps = Collections.synchronizedSet(new HashSet<SoftReference<Bitmap>>());
        }

        mMemoryCache = 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 SoftReference set for possible use with
                        // inBitmap later
                        mReusableBitmaps.add(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;
            }
        };
    }

}

From source file:mobisocial.socialkit.musubi.DbObj.java

@Override
public DbIdentity getSender() {
    DbIdentity user = null;/*from   w w  w . j  av a 2s .  c o m*/
    if (mSenderReference != null) {
        user = mSenderReference.get();
    }
    if (user == null) {
        Uri uri = Musubi.uriForItem(DbThing.IDENTITY, mSenderId);
        String selection = null;
        String[] selectionArgs = null;
        String sortOrder = null;

        Cursor c = mMusubi.getContext().getContentResolver().query(uri, DbIdentity.COLUMNS, selection,
                selectionArgs, sortOrder);
        try {
            if (!c.moveToFirst()) {
                return null;
            }

            user = DbIdentity.fromStandardCursor(mMusubi.getContext(), c);
            mSenderReference = new SoftReference<DbIdentity>(user);
        } finally {
            c.close();
        }
    }
    return user;
}

From source file:com.tingtingapps.securesms.ConversationAdapter.java

private MessageRecord getMessageRecord(long messageId, Cursor cursor, String type) {
    SoftReference<MessageRecord> reference = messageRecordCache.get(type + messageId);

    if (reference != null) {
        MessageRecord record = reference.get();

        if (record != null)
            return record;
    }/*from   w  w w . ja v  a 2s .c o  m*/

    MmsSmsDatabase.Reader reader = DatabaseFactory.getMmsSmsDatabase(context).readerFor(cursor, masterSecret);

    MessageRecord messageRecord = reader.getCurrent();

    messageRecordCache.put(type + messageId, new SoftReference<>(messageRecord));

    return messageRecord;
}

From source file:io.indy.seni.util.ImageCache.java

/**
 * Initialize the cache, providing all parameters.
 *
 * @param cacheParams The cache parameters to initialize the cache
 *//*from w  w  w.jav a  2  s  .c  o  m*/
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, create a set of reusable bitmaps that can be
        // populated into the inBitmap field of BitmapFactory.Options. Note that the set is
        // of SoftReferences which will actually not be very effective due to the garbage
        // collector being aggressive clearing Soft/WeakReferences. A better approach
        // would be to use a strongly references bitmaps, however this would require some
        // balancing of memory usage between this set and the bitmap LruCache. It would also
        // require knowledge of the expected size of the bitmaps. From Honeycomb to JellyBean
        // the size would need to be precise, from KitKat onward the size would just need to
        // be the upper bound (due to changes in how inBitmap can re-use bitmaps).
        mReusableBitmaps = Collections.synchronizedSet(new HashSet<SoftReference<Bitmap>>());

        mMemoryCache = 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) {

                // The removed entry is a standard BitmapDrawable

                // We're running on Honeycomb or later, so add the bitmap
                // to a SoftReference set for possible use with inBitmap later
                mReusableBitmaps.add(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;
            }
        };
    }
}

From source file:org.mumod.util.ImageManager.java

public void put(String url, Bitmap bitmap) {
    synchronized (this) {
        mCache.put(url, new SoftReference<Bitmap>(bitmap));
    }// ww  w  .  ja  va 2 s  .  c o m

    writeFile(url, bitmap);
}

From source file:com.googlecode.fightinglayoutbugs.WebPage.java

/**
 * Returns the source HTML of this web page.
 *//*  w ww . ja va  2s  .c om*/
@Nonnull
public String getHtml() {
    String html = (_html == null ? null : _html.get());
    if (html == null) {
        html = _driver.getPageSource();
        _html = new SoftReference<String>(html);
    }
    return html;
}

From source file:com.android.simpleimageloader.image.ImageCache.java

/**
 * Initialize the cache, providing all parameters.
 * //from  w w w .  j a  v a2 s  .c o m
 * @param cacheParams The cache parameters to initialize the cache
 */
private void init(ImageCacheParams cacheParams) {
    mCacheParams = cacheParams;

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

    // If we're running on Honeycomb or newer, create a set of reusable bitmaps that can be
    // populated into the inBitmap field of BitmapFactory.Options. Note that the set is
    // of SoftReferences which will actually not be very effective due to the garbage
    // collector being aggressive clearing Soft/WeakReferences. A better approach
    // would be to use a strongly references bitmaps, however this would require some
    // balancing of memory usage between this set and the bitmap LruCache. It would also
    // require knowledge of the expected size of the bitmaps. From Honeycomb to JellyBean
    // the size would need to be precise, from KitKat onward the size would just need to
    // be the upper bound (due to changes in how inBitmap can re-use bitmaps).
    if (Utils.hasHoneycomb()) {
        mReusableBitmaps = Collections.synchronizedSet(new HashSet<SoftReference<Bitmap>>());
    }

    mMemoryCache = 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 SoftReference set for possible use with inBitmap later
                    mReusableBitmaps.add(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;
        }
    };
    // END_INCLUDE(init_memory_cache)
    initDiskCache();
}

From source file:com.test.displaybitmaps.imagemanager.ImageCache.java

/**
 * Set up the image-cache params, providing all parameters.
 * //from w  w  w . j a va 2s .co m
 * @param cacheParams
 *            The cache parameters to initialize the cache
 */
public void setupImageCacheParams(ImageCacheParams cacheParams) {
    mCacheParams = cacheParams;

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

        // If we're running on Honeycomb or newer, create a set of reusable
        // bitmaps that can be
        // populated into the inBitmap field of BitmapFactory.Options. Note
        // that the set is
        // of SoftReferences which will actually not be very effective due
        // to the garbage
        // collector being aggressive clearing Soft/WeakReferences. A better
        // approach
        // would be to use a strongly references bitmaps, however this would
        // require some
        // balancing of memory usage between this set and the bitmap
        // LruCache. It would also
        // require knowledge of the expected size of the bitmaps. From
        // Honeycomb to JellyBean
        // the size would need to be precise, from KitKat onward the size
        // would just need to
        // be the upper bound (due to changes in how inBitmap can re-use
        // bitmaps).
        if (Build.VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB) {
            mReusableBitmaps = Collections.synchronizedSet(new HashSet<SoftReference<Bitmap>>());
        }

        mMemoryCache = 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 (Build.VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB) {
                        // We're running on Honeycomb or later, so add the
                        // bitmap
                        // to a SoftReference set for possible use with
                        // inBitmap later
                        mReusableBitmaps.add(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;
            }
        };
    }
    // END_INCLUDE(init_memory_cache)

    // 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();
    }
}