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:net.sf.jasperreports.engine.JRImageRenderer.java

/**
 *
 *//*from w  ww .  j av  a 2 s.c  o m*/
public Image getImage(JasperReportsContext jasperReportsContext) throws JRException {
    if (awtImageRef == null || awtImageRef.get() == null) {
        Image awtImage = JRImageLoader.getInstance(jasperReportsContext)
                .loadAwtImageFromBytes(getImageData(jasperReportsContext));
        awtImageRef = new SoftReference<Image>(awtImage);
    }
    return awtImageRef.get();
}

From source file:org.callimachusproject.test.TemporaryServerFactory.java

public TemporaryServer createServer() {
    return new TemporaryServer() {
        private SoftReference<TemporaryServer> ref;

        private synchronized TemporaryServer getDelegate() {
            TemporaryServer delegate = null;
            if (ref != null) {
                delegate = ref.get();// w  w  w  .  j ava2  s.  co  m
            }
            if (delegate == null) {
                delegate = createTemporaryServer();
                ref = new SoftReference<TemporaryServer>(delegate);
            }
            return delegate;
        }

        public void start() throws InterruptedException, Exception {
            getDelegate().start();
        }

        public void pause() throws Exception {
            getDelegate().pause();
        }

        public void resume() throws Exception {
            getDelegate().resume();
        }

        public void stop() throws Exception {
            getDelegate().stop();
        }

        public void destroy() throws Exception {
            getDelegate().destroy();
        }

        public String getOrigin() {
            return getDelegate().getOrigin();
        }

        public String getUsername() {
            return getDelegate().getUsername();
        }

        public char[] getPassword() {
            return getDelegate().getPassword();
        }

        @Override
        public CalliRepository getRepository() {
            return getDelegate().getRepository();
        }
    };
}

From source file:org.apache.jetspeed.security.mfa.impl.CaptchaImageResource.java

/**
 * @throws IOException//from  w ww  .  j a va 2 s .  c  o m
 * @see wicket.markup.html.image.resource.DynamicImageResource#getImageData()
 */
protected final byte[] getImageData() throws IOException {
    // get image data is always called in sync block
    byte[] data = null;
    if (imageData != null) {
        data = (byte[]) imageData.get();
    }
    if (data == null) {
        data = render();
        imageData = new SoftReference(data);
    }
    return data;
}

From source file:org.red5.cache.impl.CacheImpl.java

/** {@inheritDoc} */
public boolean offer(String name, Object obj) {
    boolean accepted = false;
    // check map size
    if (CACHE.size() < capacity) {
        SoftReference<?> tmp = CACHE.get(name);
        // because soft references can be garbage collected when a system is
        // in need of memory, we will check that the cacheable object is
        // valid//from   w  w  w .  j  av a 2 s  .  c o  m
        // log.debug("Softreference: " + (null == tmp));
        // if (null != tmp) {
        // log.debug("Softreference value: " + (null == tmp.get()));
        // }
        if (null == tmp || null == tmp.get()) {
            ICacheable cacheable = null;
            if (obj instanceof ICacheable) {
                cacheable = (ICacheable) obj;
            } else {
                cacheable = new CacheableImpl(obj);
            }
            // set the objects name
            cacheable.setName(name);
            // set a registry entry
            registry.put(name, 1);
            // create a soft reference
            SoftReference<ICacheable> value = new SoftReference<ICacheable>(cacheable);
            CACHE.put(name, value);
            // set acceptance
            accepted = true;
            log.info("{} has been added to the cache. Current size: {}", name, CACHE.size());
        }
    } else {
        log.warn("Cache has reached max element size: " + capacity);
    }
    return accepted;
}

From source file:com.abelsky.idea.geekandpoke.entries.Entry.java

private void readObject(@NotNull ObjectInputStream in) throws IOException, ClassNotFoundException {
    in.defaultReadObject();/*from  w  ww  .jav a2 s.  c  om*/
    imageRef = new SoftReference<BufferedImage>(ImageIO.read(ImageIO.createImageInputStream(in)));
}

From source file:gr.unfold.android.tsibato.images.ImageCache.java

/** Initialise the cache, providing all parameters. */
private void init(ImageCacheParams cacheParams) {
    mCacheParams = cacheParams;/*w  w w  .ja v a 2 s .c o  m*/

    if (mCacheParams.memoryCacheEnabled) {
        if (AppConfig.DEBUG) {
            Log.d(TAG, "Memory cache created (size = " + mCacheParams.memCacheSize + ")");
        }

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

        mMemoryCache = new LruCache<String, BitmapDrawable>(mCacheParams.memCacheSize) {
            @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
                        mReusableBitmaps.add(new SoftReference<Bitmap>(oldValue.getBitmap()));
                    }
                }
            }

            @Override
            protected int sizeOf(String key, BitmapDrawable value) {
                final int bitmapSize = getBitmapSize(value) / 1024;
                return bitmapSize == 0 ? 1 : bitmapSize;
            }
        };
    }

    if (cacheParams.initDiskCacheOnCreate) {
        initDiskCache();
    }
}

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

public void run() {

    BufferedReader d = null;//from   ww w . j  av a2 s  .com
    Connection conn = null;

    if (conn == null) {

        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++) {

                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) {
                    ex.printStackTrace();
                }
                Statement stmt = null;
                //                ResultSet rs = null;
                //                ResultSet rs2 = null;

                conn.setAutoCommit(false);
                stmt = conn.createStatement();
                stmt.execute("SET AUTOCOMMIT=0");
                ResultSet rs = null;
                int ServerId = 0;
                String query = null;
                ArrayList insert1 = null;
                ArrayList insert2 = null;
                int pk = 0;

                {
                    SoftReference sf = new SoftReference(
                            stmt.executeQuery("show global variables like 'SERVER_ID'"));
                    rs = (ResultSet) sf.get();
                }
                rs.next();
                ServerId = rs.getInt(2);

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

                intBlobInterval = StressTool.getNumberFromRandom(10).intValue();
                //               intBlobInterval++;
                //IMPLEMENTING lazy

                Vector v = null;
                {
                    SoftReference sf = new SoftReference(this.getTablesValues(lazy, ServerId));
                    v = (Vector) sf.get();
                }
                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=10737418");

                    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) {
                        //                      System.out.println("Blob insert value :" + intBlobInterval);
                        if (intBlobInterval > intBlobIntervalLimit) {
                            Iterator<String> it = insert2.iterator();
                            while (it.hasNext()) {
                                stmt.addBatch(it.next());
                            }
                            //                        intBlobInterval=0;

                        }
                    }

                    iLine = stmt.executeBatch();
                    stmt.clearBatch();
                    //                            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 (Exception sqle) {
                    conn.rollback();
                    if (StressTool.getErrorLogHandler() != null) {
                        StressTool.getErrorLogHandler().appendToFile(("FAILED QUERY1==" + insert1));
                        StressTool.getErrorLogHandler().appendToFile(("FAILED QUERY2==" + insert2));
                        StressTool.getErrorLogHandler().appendToFile(sqle.toString());

                    } else {
                        sqle.printStackTrace();
                        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();
                    stmt.execute("COMMIT");
                    rs.close();
                    stmt.close();
                    rs = null;
                    stmt = null;

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

                conn.close();
                conn = null;
            }

            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) {
            if (StressTool.getErrorLogHandler() != null) {
                StressTool.getErrorLogHandler().appendToFile(ex.toString() + "\n");
            } else
                ex.printStackTrace();

            try {
                conn.close();
                conn = null;
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                if (StressTool.getErrorLogHandler() != null) {
                    StressTool.getErrorLogHandler().appendToFile(e.toString() + "\n");
                    conn = null;
                } else
                    e.printStackTrace();
            }
        }

    }

}

From source file:org.red5.server.cache.CacheImpl.java

/** {@inheritDoc} */
public boolean offer(String name, Object obj) {
    boolean accepted = false;
    // check map size
    if (CACHE.size() < capacity) {
        SoftReference tmp = CACHE.get(name);
        // because soft references can be garbage collected when a system is
        // in need of memory, we will check that the cacheable object is
        // valid//  ww  w .  ja  v  a2s . c  om
        // log.debug("Softreference: " + (null == tmp));
        // if (null != tmp) {
        // log.debug("Softreference value: " + (null == tmp.get()));
        // }
        if (null == tmp || null == tmp.get()) {
            ICacheable cacheable = null;
            if (obj instanceof ICacheable) {
                cacheable = (ICacheable) obj;
            } else {
                cacheable = new CacheableImpl(obj);
            }
            // set the objects name
            cacheable.setName(name);
            // set a registry entry
            registry.put(name, 1);
            // create a soft reference
            SoftReference<ICacheable> value = new SoftReference<ICacheable>(cacheable);
            CACHE.put(name, value);
            // set acceptance
            accepted = true;
            log.info(name + " has been added to the cache. Current size: " + CACHE.size());
        }
    } else {
        log.warn("Cache has reached max element size: " + capacity);
    }
    return accepted;
}

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

public synchronized void updateSecurityTestStepResult(SecurityTestStepResult result, boolean errorsOnly,
        boolean hasChecksToProcess, boolean startStepLogEntryAdded) {
    int startStepIndex = 0;
    if (items.size() > currentStepEntriesCount) {
        if (currentStepEntriesCount > 0)
            startStepIndex = items.size() - currentStepEntriesCount;
        else/*from w  w w . ja v  a2 s  . co  m*/
            startStepIndex = items.size();
    }
    if ((errorsOnly && !result.isHasScansWithWarnings()) || (startStepLogEntryAdded && !hasChecksToProcess)) {
        // stepCount-- ;
        int size = items.size() - 1;
        while (size >= startStepIndex) {
            items.remove(size);
            results.remove(size);
            size--;
        }
        if (startStepIndex > 0 && size > 0) {
            fireIntervalRemoved(this, startStepIndex, size);
        } else {
            fireIntervalRemoved(this, 0, size);
        }
    } else if (startStepLogEntryAdded) {

        try {
            if (startStepIndex > 0 && startStepIndex < maxSize) {
                String statusToDisplay = getStatusToDisplay(result.getExecutionProgressStatus());
                items.set(startStepIndex, "Step " + stepCount + " [" + result.getTestStep().getName() + "] "
                        + statusToDisplay + ": took " + result.getTimeTaken() + " ms");
                SoftReference<SecurityResult> stepResultRef = new SoftReference<SecurityResult>(result);
                results.set(startStepIndex, stepResultRef);
                fireContentsChanged(this, startStepIndex, startStepIndex);
            }
        } catch (IndexOutOfBoundsException e) {
            // when log max size is exceeded skip updating the raw since it
            // won't be visible anyway
        }
    }
    currentStepEntriesCount = 0;
}

From source file:org.caleydo.view.tourguide.impl.Statistics.java

public static double chiSquaredProbability(double x, int df) {
    // return weka.core.Statistics.chiSquaredProbability(x, df);
    ChiSquaredDistribution d;//w  w  w . j a  va 2s .c  o m
    if (df == 1) {
        d = chiSquare1 != null ? chiSquare1.get() : null;
        if (d == null) {
            d = new ChiSquaredDistributionImpl(1);
            chiSquare1 = new SoftReference<>(d);
        }
    } else {
        d = new ChiSquaredDistributionImpl(df);
    }
    try {
        return 1.0 - d.cumulativeProbability(x);
    } catch (MathException e) {
        log.error("can't compute chiSquaredProbability of " + x + " with df: " + df, e);
    }
    return Float.NaN;
}