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:com.mysql.stresstool.RunnableQueryInsertPCH.java

public void run() {

    BufferedReader d = null;/*  www  .j a va  2 s . c om*/
    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:de.cismet.cids.custom.objecteditors.wunda_blau.WebDavPicturePanel.java

/**
 * DOCUMENT ME!/*www . j a  v a2s .co m*/
 */
private void loadFoto() {
    final Object fotoObj = lstFotos.getSelectedValue();
    if (fotoCidsBean != null) {
        fotoCidsBean.removePropertyChangeListener(listRepaintListener);
    }
    if (fotoObj instanceof CidsBean) {
        fotoCidsBean = (CidsBean) fotoObj;
        fotoCidsBean.addPropertyChangeListener(listRepaintListener);
        final String fileObj = (String) fotoCidsBean.getProperty("url.object_name");
        boolean cacheHit = false;
        if (fileObj != null) {
            final SoftReference<BufferedImage> cachedImageRef = IMAGE_CACHE.get(fileObj);
            if (cachedImageRef != null) {
                final BufferedImage cachedImage = cachedImageRef.get();
                if (cachedImage != null) {
                    cacheHit = true;
                    image = cachedImage;
                    showWait(true);
                    resizeListenerEnabled = true;
                    timer.restart();
                }
            }
            if (!cacheHit) {
                CismetThreadPool.execute(new LoadSelectedImageWorker(fileObj));
            }
        }
    } else {
        image = null;
        lblPicture.setIcon(FOLDER_ICON);
    }
}

From source file:pl.otros.logview.api.gui.LogViewPanelWrapper.java

public LogViewPanelWrapper(final String name, final Stoppable stoppable, final TableColumns[] visibleColumns,
        final LogDataTableModel logDataTableModel, final DataConfiguration configuration,
        final OtrosApplication otrosApplication) {

    this.name = name;
    this.configuration = configuration;
    this.otrosApplication = otrosApplication;
    logLoader = otrosApplication.getLogLoader();
    this.addHierarchyListener(e -> {
        if (e.getChangeFlags() == 1 && e.getChanged().getParent() == null) {
            closing();/*from  ww  w .j a v  a  2 s  .c o  m*/
        }
    });
    final TableColumns[] columns = (visibleColumns == null) ? TableColumns.ALL_WITHOUT_LOG_SOURCE
            : visibleColumns;

    fillDefaultConfiguration();

    SoftReference<Stoppable> stoppableReference = new SoftReference<>(stoppable);
    // this.statusObserver = statusObserver;
    dataTableModel = logDataTableModel == null ? new LogDataTableModel() : logDataTableModel;
    logViewPanel = new LogViewPanel(dataTableModel, columns, otrosApplication);

    cardLayout = new CardLayout();
    GridBagConstraints c = new GridBagConstraints();
    c.insets = new Insets(10, 10, 10, 10);
    c.anchor = GridBagConstraints.PAGE_START;
    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridx = 0;
    c.gridy = 0;
    c.ipadx = 1;
    c.ipady = 1;
    c.weightx = 10;
    c.weighty = 1;

    c.gridy++;
    c.weighty = 3;
    loadingProgressBar = new JProgressBar();
    loadingProgressBar.setIndeterminate(false);
    loadingProgressBar.setStringPainted(true);
    loadingProgressBar.setString("Connecting...");

    c.gridy++;
    c.weighty = 1;
    c.weightx = 2;
    c.gridy++;
    c.weightx = 1;
    JButton stopButton = new JButton("Stop, you have imported already enough!");
    stopButton.addActionListener(e -> {
        Stoppable stoppable1 = stoppableReference.get();
        if (stoppable1 != null) {
            stoppable1.stop();
        }
    });

    setLayout(cardLayout);
    add(logViewPanel, CARD_LAYOUT_CONTENT);
    cardLayout.show(this, CARD_LAYOUT_LOADING);

}

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

public void run() {

    BufferedReader d = null;//from   w  w w .  j  av a 2s . c  o  m
    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.yacy.http.servlets.YaCyDefaultServlet.java

protected Method rewriteMethod(final File classFile) throws InvocationTargetException {
    Method m = null;//www .j a  va 2  s.co  m
    // now make a class out of the stream
    try {
        final SoftReference<Method> ref = templateMethodCache.get(classFile);
        if (ref != null) {
            m = ref.get();
            if (m == null) {
                templateMethodCache.remove(classFile);
            } else {
                return m;
            }
        }

        final Class<?> c = provider.loadClass(classFile);

        final Class<?>[] params = (Class<?>[]) Array.newInstance(Class.class, 3);
        params[0] = RequestHeader.class;
        params[1] = serverObjects.class;
        params[2] = serverSwitch.class;
        m = c.getMethod("respond", params);

        if (MemoryControl.shortStatus()) {
            templateMethodCache.clear();
        } else {
            // store the method into the cache
            templateMethodCache.put(classFile, new SoftReference<Method>(m));
        }
    } catch (final ClassNotFoundException e) {
        ConcurrentLog.severe("FILEHANDLER",
                "YaCyDefaultServlet: class " + classFile + " is missing:" + e.getMessage());
        throw new InvocationTargetException(e, "class " + classFile + " is missing:" + e.getMessage());
    } catch (final NoSuchMethodException e) {
        ConcurrentLog.severe("FILEHANDLER",
                "YaCyDefaultServlet: method 'respond' not found in class " + classFile + ": " + e.getMessage());
        throw new InvocationTargetException(e,
                "method 'respond' not found in class " + classFile + ": " + e.getMessage());
    }
    return m;
}

From source file:org.apache.sysml.runtime.matrix.data.FrameBlock.java

/**
 * This function will split every Recode map in the column using delimiter Lop.DATATYPE_PREFIX, 
 * as Recode map generated earlier in the form of Code+Lop.DATATYPE_PREFIX+Token and store it in a map 
 * which contains token and code for every unique tokens.
 *
 * @param col   is the column # from frame data which contains Recode map generated earlier.
 * @return map of token and code for every element in the input column of a frame containing Recode map
 *//*  ww  w.  ja v a 2s  . c o  m*/
public HashMap<String, Long> getRecodeMap(int col) {
    //probe cache for existing map
    if (REUSE_RECODE_MAPS) {
        SoftReference<HashMap<String, Long>> tmp = _rcdMapCache.get(col);
        HashMap<String, Long> map = (tmp != null) ? tmp.get() : null;
        if (map != null)
            return map;
    }

    //construct recode map
    HashMap<String, Long> map = new HashMap<String, Long>();
    Array ldata = _coldata[col];
    for (int i = 0; i < getNumRows(); i++) {
        Object val = ldata.get(i);
        if (val != null) {
            //            String[] tmp = IOUtilFunctions.splitCSV(
            //                  val.toString(), Lop.DATATYPE_PREFIX);

            // Instead of using splitCSV which is forcing string with RFC-4180 format, using Lop.DATATYPE_PREFIX separator to split token and code 
            String[] tmp = new String[2];
            int pos = val.toString().lastIndexOf(Lop.DATATYPE_PREFIX);
            tmp[0] = val.toString().substring(0, pos);
            tmp[1] = val.toString().substring(pos + 1);
            map.put(tmp[0], Long.parseLong(tmp[1]));
        }
    }

    //put created map into cache
    if (REUSE_RECODE_MAPS) {
        _rcdMapCache.put(col, new SoftReference<HashMap<String, Long>>(map));
    }

    return map;
}

From source file:com.com.easemob.chatuidemo.adapter.MessageAdapter.java

public Bitmap loadBitmap(final String imageURL) {
    imageCache = new HashMap<String, SoftReference<Bitmap>>();
    Bitmap bitmap;/*from   w  w w.j a v  a  2 s.  c  om*/
    option.inSampleSize = 5;
    if (imageCache.containsKey(imageURL)) {
        SoftReference<Bitmap> reference = imageCache.get(imageURL);
        bitmap = null;
        bitmap = reference.get();
        if (bitmap != null) {
            return bitmap;
        }
    } else {
        String bitmapName = imageURL.substring(imageURL.lastIndexOf("/") + 1);
        File cacheDir = new File(Environment.getExternalStorageDirectory() + "/kaoban/");
        File[] cacheFiles = cacheDir.listFiles();
        int i = 0;
        if (null != cacheFiles) {
            for (; i < cacheFiles.length; i++) {
                if (bitmapName.equals(cacheFiles[i].getName())) {
                    break;
                }
            }
            if (i < cacheFiles.length) {
                return BitmapFactory.decodeFile(
                        Environment.getExternalStorageDirectory() + "/kaoban/" + bitmapName, option);
            }
        }
    }
    return null;
}

From source file:org.codehaus.groovy.grails.web.util.StreamCharBuffer.java

void notifyBufferChange() {
    if (!notifyParentBuffersEnabled)
        return;//  w w  w  . j  a va  2  s.co m

    if (parentBuffers == null) {
        return;
    }

    for (Iterator<SoftReference<StreamCharBufferKey>> i = parentBuffers.iterator(); i.hasNext();) {
        SoftReference<StreamCharBufferKey> ref = i.next();
        final StreamCharBuffer.StreamCharBufferKey parentKey = ref.get();
        boolean removeIt = true;
        if (parentKey != null) {
            StreamCharBuffer parent = parentKey.getBuffer();
            removeIt = !parent.bufferChanged(this);
        }
        if (removeIt) {
            i.remove();
        }
    }
}

From source file:org.grails.buffer.StreamCharBuffer.java

protected List<StreamCharBuffer> getCurrentParentBuffers() {
    List<StreamCharBuffer> currentParentBuffers = new ArrayList<StreamCharBuffer>();
    if (parentBuffers != null) {
        for (Iterator<SoftReference<StreamCharBufferKey>> i = parentBuffers.iterator(); i.hasNext();) {
            SoftReference<StreamCharBufferKey> ref = i.next();
            final StreamCharBuffer.StreamCharBufferKey parentKey = ref.get();
            if (parentKey != null) {
                currentParentBuffers.add(parentKey.getBuffer());
            }//from w ww .j  a  v  a 2 s .  c  o  m
        }
    }
    return currentParentBuffers;
}