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:org.xenei.bloomgraph.SerializableNode.java

/**
 * Create a serializable node from a node and limit the buffer size. If the
 * serialized node is a literal and exceeds the maximum buffer size the data
 * are compressed before writing and decompressed on reading.
 * /*  w  w w.j  a  v  a  2s .c o m*/
 * @param n
 *            the node to wrap.
 * @param maxBlob
 *            The maximum buffer size.
 * @throws IOException
 *             on error.
 */
public SerializableNode(Node n, int maxBlob) throws IOException {
    this.node = new SoftReference<Node>(n);
    if (n.equals(Node.ANY)) {
        fillBuffer(Node.ANY.hashCode(), _ANY, null);
    } else if (n.isVariable()) {
        fillBuffer(n.hashCode(), _VAR, encodeString(n.getName()));
    } else if (n.isURI()) {
        fillBuffer(n.hashCode(), _URI, encodeString(n.getURI()));
    } else if (n.isBlank()) {
        fillBuffer(n.hashCode(), _ANON, encodeString(n.getBlankNodeId().getLabelString()));
    } else if (n.isLiteral()) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream os = new DataOutputStream(baos);
        write(os, n.getLiteralLexicalForm());
        write(os, n.getLiteralLanguage());
        write(os, n.getLiteralDatatypeURI());

        os.close();
        baos.close();
        byte[] value = baos.toByteArray();
        if (value.length > maxBlob) {
            baos = new ByteArrayOutputStream();
            GZIPOutputStream dos = new GZIPOutputStream(baos);
            dos.write(value);
            dos.close();
            fillBuffer(n.hashCode(), (byte) (_LIT | _COMPRESSED), baos.toByteArray());
        } else {
            fillBuffer(n.hashCode(), _LIT, value);
        }
    } else {
        throw new IllegalArgumentException("Unknown node type " + n);
    }
}

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

/**
 * Returns the main feed that bounds this object.
 *//*  ww  w.jav  a  2 s.co  m*/
public DbFeed getContainingFeed() {
    DbFeed f = null;
    if (mContainingFeed != null) {
        f = mContainingFeed.get();
    }
    if (f == null) {
        f = mMusubi.getFeed(mFeedUri);
        mContainingFeed = new SoftReference<DbFeed>(f);
    }
    return f;
}

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.//  ww w. j  a v  a 2 s  .  c  om
 *
 * @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();
            }
        }

    }

}

From source file:org.diorite.impl.world.chunk.palette.MapPaletteImpl.java

@Override
public void write(final PacketDataSerializer data) {
    int[] mapping = (this.ref == null) ? null : this.ref.get();
    if (mapping == null) {
        synchronized (this.pattern) {
            mapping = new int[this.pattern.size()];
            for (final Entry entry : this.pattern.int2IntEntrySet()) {
                mapping[entry.getIntKey()] = entry.getIntValue();
            }/*from   w  ww.j a  v a  2  s  . co  m*/
            this.ref = new SoftReference<>(mapping);
        }
    }
    data.writeVarInt(mapping.length);
    for (final int i : mapping) {
        data.writeVarInt(i);
    }
}

From source file:net.sf.nmedit.jpatch.ModuleDescriptions.java

private Map<ImageSource, Image> getImageCache() {
    Map<ImageSource, Image> cache = (imageCacheReference != null) ? imageCacheReference.get() : null;
    if (cache == null) {
        cache = new HashMap<ImageSource, Image>();
        imageCacheReference = new SoftReference<Map<ImageSource, Image>>(cache);
    }/*from w ww.  j  a  v  a  2 s . com*/
    return cache;
}

From source file:edu.ku.brc.specify.tasks.BaseTask.java

/**
 * @return the Hashtable from the SoftReference
 *///from   ww  w .  ja  v  a2  s  . c  om
protected Hashtable<String, PermissionOptionPersist> getAndSetDefPerms() {
    if (taskPermsListSR == null) {
        taskPermsListSR = new SoftReference<Hashtable<String, PermissionOptionPersist>>(null);
    }

    Hashtable<String, PermissionOptionPersist> hash = taskPermsListSR.get();

    if (hash == null) {
        Hashtable<String, Hashtable<String, PermissionOptionPersist>> taskHash = readDefaultPermsFromXML(
                "tasks.xml");
        if (taskHash != null) {
            hash = taskHash.get(name);
            if (hash != null) {
                taskPermsListSR = new SoftReference<Hashtable<String, PermissionOptionPersist>>(hash);
            }
        }
    }

    return hash;
}

From source file:com.chanlytech.unicorn.cache.ImageCache.java

@Override
protected LruCache<String, BitmapDrawable> getLurCache() {
    return new LruCache<String, BitmapDrawable>(mCacheParams.MEMORY_CACHE_SIZE) {
        /**/*  w  ww. j  av a2s .  c  o  m*/
         * 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 (AndroidVersion.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:com.abelsky.idea.geekandpoke.entries.Entry.java

private void writeObject(@NotNull ObjectOutputStream out) throws IOException {
    out.defaultWriteObject();//from   ww w. j  a v  a  2 s. co m
    if (imageRef != null) {
        @Nullable
        BufferedImage image = imageRef.get();
        if (image == null) {
            image = fetchCachedImage();
            imageRef = new SoftReference<BufferedImage>(image);
        }
        ImageIO.write(image, "png", ImageIO.createImageOutputStream(out));
    }
}

From source file:com.higgses.griffin.cache.ImageCache.java

@Override
protected LruCache<String, BitmapDrawable> getLurCache() {
    return new LruCache<String, BitmapDrawable>(mCacheParams.MEMORY_CACHE_SIZE) {
        /**//w w  w  .  j a  v  a 2 s  .  c om
         * 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 (GriUAndroidVersion.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:com.seun.gallery.util.ImageCache.java

/**
 * Initialize the cache//from w w  w  .  j a va  2  s  .c  o  m
 */
private void init(int memoryCacheSize) {
    //BEGIN_INCLUDE(init_memory_cache)
    // Set up memory cache
    if (DEBUG) {
        Log.d(TAG, "Memory cache created (size = " + memoryCacheSize + ")");
    }

    // 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 >= Build.VERSION_CODES.HONEYCOMB) {
        mReusableBitmaps = Collections.synchronizedSet(new HashSet<SoftReference<Bitmap>>());
    }

    mMemoryCache = new LruCache<String, BitmapDrawable>(memoryCacheSize) {

        /**
         * 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 >= Build.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)
}