Example usage for java.lang System gc

List of usage examples for java.lang System gc

Introduction

In this page you can find the example usage for java.lang System gc.

Prototype

public static void gc() 

Source Link

Document

Runs the garbage collector in the Java Virtual Machine.

Usage

From source file:com.xilinx.virtex7.MainScreen.java

public void initialize(LandingPage l, String imgName, int mode) {
    lp = l;/*from  w w w.  j a v  a  2s.co  m*/
    blockDiagram = Toolkit.getDefaultToolkit()
            .getImage(getClass().getResource("/com/xilinx/virtex7/" + imgName));
    led1 = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/com/xilinx/gui/green.png"));
    led2 = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/com/xilinx/gui/ledoff.png"));
    led3 = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/com/xilinx/gui/red.png"));
    this.mode = mode;
    setModeText(mode);
    dataMismatch0 = dataMismatch2 = errcnt0 = errcnt1 = false;
    dataMismatch4 = dataMismatch6 = errcnt2 = errcnt3 = false;
    di = null;
    di = new DriverInfo();
    di.init(mode);
    int ret = di.get_PCIstate();

    //ret = di.get_PowerStats();
    test1_option = DriverInfo.ENABLE_LOOPBACK;
    test2_option = DriverInfo.ENABLE_LOOPBACK;
    test3_option = DriverInfo.ENABLE_LOOPBACK;
    test4_option = DriverInfo.ENABLE_LOOPBACK;
    // create a new jframe, and pack it
    frame = new JFrame("Virtex-7 XT Connectivity TRD Control & Monitoring Interface");
    frame.pack();
    frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    final int m = mode;
    frame.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            // check if tests are running or not

            if ((testStarted || testStarted1 || testStarted2 || testStarted3)
                    && ((m != LandingPage.APPLICATION_MODE) || (m != LandingPage.APPLICATION_MODE_P2P))) {
                int confirmed = JOptionPane.showConfirmDialog(null,
                        "This will stop the tests and uninstall the drivers. Do you want to continue?", "Exit",
                        JOptionPane.YES_NO_OPTION);
                if (confirmed == JOptionPane.YES_OPTION) {
                    if (testStarted) {
                        di.stopTest(0, test1_option, Integer.parseInt(t1_psize.getText()));
                        testStarted = false;
                    }
                    if (testStarted1) {
                        di.stopTest(1, test2_option, Integer.parseInt(t2_psize.getText()));
                        testStarted1 = false;
                    }

                    if (testStarted2) {
                        di.stopTest(2, test3_option, Integer.parseInt(t3_psize.getText()));
                        testStarted2 = false;
                    }
                    if (testStarted3) {
                        di.stopTest(3, test4_option, Integer.parseInt(t4_psize.getText()));
                        testStarted3 = false;
                    }

                    timer.cancel();
                    textArea.removeAll();
                    di.flush();
                    di = null;
                    System.gc();
                    lp.uninstallDrivers();
                    showDialog("Removing Device Drivers...Please wait...");
                }
            } else {
                int confirmed = JOptionPane.showConfirmDialog(null,
                        "This will Uninstall the drivers. Do you want to continue?", "Exit",
                        JOptionPane.YES_NO_OPTION);
                if (confirmed == JOptionPane.YES_OPTION) {
                    timer.cancel();
                    textArea.removeAll();
                    di.flush();
                    di = null;
                    System.gc();
                    lp.uninstallDrivers();
                    showDialog("Removing Device Drivers...Please wait...");
                }
            }
        }
    });

    // make the frame half the height and width
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    height = screenSize.height;
    width = screenSize.width;

    minWidth = 1000;
    minHeight = 600;
    minFrameWidth = 1024;
    minFrameHeight = 745;

    reqHeight = 745;
    if (width < 1280)
        reqWidth = 1024;
    else if (width == 1280)
        reqWidth = 1280;
    else if (width < 1600) {
        reqWidth = width - (width * 4) / 100;
        reqHeight = height - (height * 3) / 100;
    } else {
        reqWidth = reqHeight = height = height - (height * 10) / 100;
    }

    frame.setSize(new Dimension(minFrameWidth, minFrameHeight));
    frame.setResizable(true);
    frame.addComponentListener(new ComponentListener() {

        @Override
        public void componentResized(ComponentEvent ce) {
            frame.setSize(new Dimension(Math.max(minFrameWidth, frame.getWidth()),
                    Math.max(minFrameHeight, frame.getHeight())));
        }

        @Override
        public void componentMoved(ComponentEvent ce) {
            //throw new UnsupportedOperationException("Not supported yet.");
        }

        @Override
        public void componentShown(ComponentEvent ce) {
            //throw new UnsupportedOperationException("Not supported yet.");
        }

        @Override
        public void componentHidden(ComponentEvent ce) {
            //throw new UnsupportedOperationException("Not supported yet.");
        }
    });
    frame.setVisible(true);

    frame.setIconImage(
            Toolkit.getDefaultToolkit().getImage(getClass().getResource("/com/xilinx/virtex7/icon.png")));
    // center the jframe on screen
    frame.setLocationRelativeTo(null);

    frame.setContentPane(createContentPane());

    keyWord = new SimpleAttributeSet();
    StyleConstants.setForeground(keyWord, Color.RED);

    StyleConstants.setBold(keyWord, true);

    logStatus = new SimpleAttributeSet();
    StyleConstants.setForeground(logStatus, Color.BLACK);
    StyleConstants.setBold(logStatus, true);

    if ((mode == LandingPage.APPLICATION_MODE) || (mode == LandingPage.APPLICATION_MODE_P2P)) {
        testStarted = testStarted1 = testStarted2 = testStarted3 = true;
    }

    if (mode == LandingPage.PERFORMANCE_MODE_RAW) {
        t1_o1.setSelected(true);
        t1_o2.setEnabled(false);
        t1_o3.setEnabled(false);
        t2_o2.setEnabled(false);
        t2_o3.setEnabled(false);
    }
    if (mode == LandingPage.PERFORMANCE_MODE_RAW_DV) {
        t1_o2.setEnabled(false);
        t1_o3.setEnabled(false);
        t2_o2.setEnabled(false);
        t2_o3.setEnabled(false);
        t1_o1.setSelected(true);
    }

    // initialize max packet size
    ret = di.get_EngineState();
    EngState[] engData = di.getEngState();
    maxpkt0 = engData[0].MaxPktSize;
    minpkt0 = engData[0].MinPktSize;

    minpkt1 = engData[2].MinPktSize;
    maxpkt1 = engData[2].MaxPktSize;

    maxpkt2 = engData[4].MaxPktSize;
    minpkt2 = engData[4].MinPktSize;

    minpkt3 = engData[6].MinPktSize;
    maxpkt3 = engData[6].MaxPktSize;

    t1_psize.setText(String.valueOf(maxpkt0));
    t2_psize.setText(String.valueOf(maxpkt1));
    t3_psize.setText(String.valueOf(maxpkt2));
    t4_psize.setText(String.valueOf(maxpkt3));

    t1_psize.setToolTipText(minpkt0 + "-" + maxpkt0);
    t2_psize.setToolTipText(minpkt1 + "-" + maxpkt1);
    t3_psize.setToolTipText(minpkt2 + "-" + maxpkt2);
    t4_psize.setToolTipText(minpkt3 + "-" + maxpkt3);

    updateLog(di.getPCIInfo().getVersionInfo(), logStatus);
    updateLog("Configuration: " + modeText, logStatus);

    // LED status
    di.get_LedStats();
    lstats = di.getLedStats();
    setLedStats(lstats);

    //
    if (mode == LandingPage.PERFORMANCE_MODE_RAW || mode == LandingPage.PERFORMANCE_MODE_RAW_DV) {
        t2_o1.setEnabled(true);
        t4_o1.setEnabled(true);
    } else {
        t2_o1.setEnabled(false);
        t4_o1.setEnabled(false);
    }
    t2_o2.setEnabled(false);
    t2_o3.setEnabled(false);
    t3_o2.setEnabled(false);
    t3_o3.setEnabled(false);
    t4_o2.setEnabled(false);
    t4_o3.setEnabled(false);
    startTimer();
}

From source file:com.panet.imeta.job.entries.addresultfilenames.JobEntryAddResultFilenames.java

private boolean ProcessFile(String filename, String wildcard, Job parentJob, Result result) {
    LogWriter log = LogWriter.getInstance();

    boolean rcode = false;
    FileObject filefolder = null;
    String realFilefoldername = environmentSubstitute(filename);
    String realwildcard = environmentSubstitute(wildcard);

    try {/*from   ww  w  . j a  v  a  2s .  c  om*/
        filefolder = KettleVFS.getFileObject(realFilefoldername);

        // Here gc() is explicitly called if e.g. createfile is used in the
        // same
        // job for the same file. The problem is that after creating the
        // file the
        // file object is not properly garbaged collected and thus the file
        // cannot
        // be deleted anymore. This is a known problem in the JVM.

        System.gc();

        if (filefolder.exists()) {
            // the file or folder exists

            if (filefolder.getType() == FileType.FILE) {
                // Add filename to Resultfilenames ...
                if (log.isDetailed())
                    log.logDetailed(toString(), Messages
                            .getString("JobEntryAddResultFilenames.AddingFileToResult", filefolder.toString()));
                ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL,
                        KettleVFS.getFileObject(filefolder.toString()), parentJob.getJobname(), toString());
                result.getResultFiles().put(resultFile.getFile().toString(), resultFile);
            } else {
                FileObject list[] = filefolder
                        .findFiles(new TextFileSelector(filefolder.toString(), realwildcard));

                for (int i = 0; i < list.length && !parentJob.isStopped(); i++) {
                    // Add filename to Resultfilenames ...
                    if (log.isDetailed())
                        log.logDetailed(toString(), Messages.getString(
                                "JobEntryAddResultFilenames.AddingFileToResult", list[i].toString()));
                    ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL,
                            KettleVFS.getFileObject(list[i].toString()), parentJob.getJobname(), toString());
                    result.getResultFiles().put(resultFile.getFile().toString(), resultFile);
                }
            }

        } else {
            // File can not be found
            if (log.isBasic())
                log.logBasic(toString(),
                        Messages.getString("JobEntryAddResultFilenames.FileCanNotbeFound", realFilefoldername)); //$NON-NLS-1$
            rcode = true;
        }
    } catch (IOException e) {
        log.logError(toString(), Messages.getString("JobEntryAddResultFilenames.CouldNotProcess", //$NON-NLS-1$
                realFilefoldername, e.getMessage()));
    } finally {
        if (filefolder != null) {
            try {
                filefolder.close();
            } catch (IOException ex) {
            }
            ;
        }
    }

    return rcode;
}

From source file:com.gs.collections.impl.parallel.SerialParallelLazyPerformanceTest.java

private static void forceGC() {
    IntInterval.oneTo(20).forEach((IntProcedure) each -> {
        System.gc();
        try {//  w w  w .j  av  a2 s  . c  o  m
            Thread.sleep(100);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    });
}

From source file:com.searchcode.app.jobs.repository.IndexGitRepoJob.java

/**
 * Uses the inbuilt git//  ww  w .  j  a v a 2 s .c  o m
 * TODO this method appears to leak memory like crazy... need to investigate
 * TODO lots of hairy bits in here need tests to capture issues
 */
public List<CodeOwner> getBlameInfo(int codeLinesSize, String repoName, String repoLocations, String fileName) {
    List<CodeOwner> codeOwners = new ArrayList<>(codeLinesSize);
    try {
        // The / part is required due to centos bug for version 1.1.1
        // This appears to be correct
        String repoLoc = repoLocations + "/" + repoName + "/.git";

        Repository localRepository = new FileRepository(new File(repoLoc));
        BlameCommand blamer = new BlameCommand(localRepository);

        ObjectId commitID = localRepository.resolve("HEAD");

        if (commitID == null) {
            Singleton.getLogger().info("getBlameInfo commitID is null for " + repoLoc + " " + fileName);
            return codeOwners;
        }

        BlameResult blame;

        // Somewhere in here appears to be wrong...
        blamer.setStartCommit(commitID);
        blamer.setFilePath(fileName);
        blame = blamer.call();

        // Hail mary attempt to solve issue on CentOS Attempt to set at all costs
        if (blame == null) { // This one appears to solve the issue so don't remove it
            String[] split = fileName.split("/");
            blamer.setStartCommit(commitID);
            if (split.length != 1) {
                blamer.setFilePath(String.join("/", Arrays.asList(split).subList(1, split.length)));
            }
            blame = blamer.call();
        }
        if (blame == null) {
            String[] split = fileName.split("/");
            blamer.setStartCommit(commitID);
            if (split.length != 1) {
                blamer.setFilePath("/" + String.join("/", Arrays.asList(split).subList(1, split.length)));
            }
            blame = blamer.call();
        }

        if (blame == null) {
            Singleton.getLogger().info("getBlameInfo blame is null for " + repoLoc + " " + fileName);
        }

        if (blame != null) {
            // Get all the owners their number of commits and most recent commit
            HashMap<String, CodeOwner> owners = new HashMap<>();
            RevCommit commit;
            PersonIdent authorIdent;

            try {
                for (int i = 0; i < codeLinesSize; i++) {
                    commit = blame.getSourceCommit(i);
                    authorIdent = commit.getAuthorIdent();

                    if (owners.containsKey(authorIdent.getName())) {
                        CodeOwner codeOwner = owners.get(authorIdent.getName());
                        codeOwner.incrementLines();

                        int timestamp = codeOwner.getMostRecentUnixCommitTimestamp();

                        if (commit.getCommitTime() > timestamp) {
                            codeOwner.setMostRecentUnixCommitTimestamp(commit.getCommitTime());
                        }
                        owners.put(authorIdent.getName(), codeOwner);
                    } else {
                        owners.put(authorIdent.getName(),
                                new CodeOwner(authorIdent.getName(), 1, commit.getCommitTime()));
                    }
                }
            } catch (IndexOutOfBoundsException ex) {
                // Ignore this as its not really a problem or is it?
                Singleton.getLogger().info(
                        "IndexOutOfBoundsException when trying to get blame for " + repoName + " " + fileName);
            }

            codeOwners = new ArrayList<>(owners.values());
        }

    } catch (IOException ex) {
        Singleton.getLogger().info("IOException getBlameInfo when trying to get blame for " + repoName + " "
                + fileName + " " + ex.toString());
    } catch (GitAPIException ex) {
        Singleton.getLogger().info("GitAPIException getBlameInfo when trying to get blame for " + repoName + " "
                + fileName + " " + ex.toString());
    } catch (IllegalArgumentException ex) {
        Singleton.getLogger().info("IllegalArgumentException getBlameInfo when trying to get blame for "
                + repoName + " " + fileName + " " + ex.toString());
    }

    System.gc(); // Try to clean up
    return codeOwners;
}

From source file:com.univocity.app.swing.DataAnalysisWindow.java

protected void executeProcess(String processName) {
    final Runnable process = config.getProcess(processName);
    getGlass().activate("Executing process: '" + processName + "'...");

    Thread thread = new Thread() {
        @Override//from w w w. j av a 2 s . com
        public void run() {
            try {
                long start = System.currentTimeMillis();
                SwingUtilities.invokeAndWait(process);
                long timeTaken = System.currentTimeMillis() - start;
                setStatus("Completed.", "Took " + timeTaken / 1000 + " seconds (" + timeTaken + " ms)");
            } catch (InterruptedException ie) {
                Thread.currentThread().interrupt();
                setStatus("Interrupted", "");
            } catch (InvocationTargetException ie) {
                WindowUtils.showErrorMessage(DataAnalysisWindow.this, ie.getCause());
                setStatus("Interrupted", "");
            } finally {
                getGlass().deactivate();
            }
            System.gc();
        }
    };
    thread.start();
}

From source file:burstcoin.jminer.core.round.Round.java

@EventListener
public void handleMessage(ReaderStoppedEvent event) {
    System.gc();
    fireEvent(new RoundStoppedEvent(event.getBlockNumber(), event.getLastBestCommittedDeadline(),
            event.getCapacity(), event.getRemainingCapacity(), event.getElapsedTime()));
}

From source file:edu.umd.lib.servlets.permissions.PermissionsServlet.java

@Override
public void destroy() {
    // close repository
    log.info("Closing repository.");
    if (repository != null) {
        repository.close();//from   w  w  w. j ava  2 s .c  om
        repository = null;
    }

    // done
    log.info("Repository closed.");

    if (startRemoteServer) {
        // unbinding from registry
        String name = null;
        try {
            name = new RepositoryUrl(bindingAddress).getName();
            log.info("Unbinding '" + name + "' from registry.");
            registry.unbind(name);
        } catch (RemoteException e) {
            log.error("Error during unbinding '" + name + "': " + e.getMessage());
        } catch (NotBoundException e) {
            log.error("Error during unbinding '" + name + "': " + e.getMessage());
        } catch (MalformedURLException e) {
            log.error("MalformedURLException while parsing '" + bindingAddress + "': " + e.getMessage());
        }

        // unexporting from registry
        try {
            log.info("Unexporting rmi repository: " + bindingAddress);
            UnicastRemoteObject.unexportObject(rmiRepository, true);
        } catch (NoSuchObjectException e) {
            log.error("Error during rmi shutdown for address: " + bindingAddress, e);
        }

        // shutdown registry
        if (registryIsEmbedded) {
            try {
                log.info("Closing rmiregistry: " + bindingAddress);
                UnicastRemoteObject.unexportObject(registry, true);
            } catch (NoSuchObjectException e) {
                log.error("Error during rmi shutdown for address: " + bindingAddress, e);
            }
        }

        // force the distributed GC to fire, otherwise in tomcat with embedded
        // rmi registry the process won't end
        // this procedure is necessary specifically for Tomcat
        log.info("Repository terminated, waiting for garbage to clear");
        Thread garbageClearThread = new Thread("garbage clearer") {
            @Override
            public void run() {
                for (int i = 0; i < 5; i++) {
                    try {
                        Thread.sleep(3000);
                        System.gc();
                    } catch (InterruptedException ignored) {
                    }
                }
            }
        };
        garbageClearThread.setDaemon(true);
        garbageClearThread.start();

    }

    if (repositoryService != null) {
        HippoServiceRegistry.unregisterService(repositoryService, RepositoryService.class);
    }
    if (repositoryClusterService != null) {
        HippoServiceRegistry.unregisterService(repositoryClusterService, RepositoryClusterService.class);
    }
}

From source file:ch.ethz.dcg.jukefox.commons.utils.AndroidUtils.java

public static Bitmap getBitmapFromByteArray(byte[] byteArray, int maxSize) {
    Bitmap bitmap = null;/*from w  w w.  j a  v a 2 s  .  c om*/
    try {
        try {

            int sampleFactor = getSampleFactor(byteArray, maxSize);
            BitmapFactory.Options resample = new BitmapFactory.Options();
            resample.inSampleSize = sampleFactor;
            bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length, resample);
        } catch (Error e) {

            // Avoid that heap has to be grown for the BitmapFactory,
            // as this would lead to an out of memory error
            int[] dummyArray = new int[byteArray.length];
            // Avoid being eliminated by optimization of compiler
            if (dummyArray != null) {
                dummyArray = null;
                System.gc();
            }
            Log.w("BitmapFactory", e);
        }
        if (bitmap == null) {
            try {
                int sampleFactor = getSampleFactor(byteArray, maxSize);
                BitmapFactory.Options resample = new BitmapFactory.Options();
                resample.inSampleSize = sampleFactor;
                bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length, resample);
            } catch (Error e) {
                System.gc();
                Log.w("BitmapFactory", e);
            }
        }
    } catch (Throwable e) {
        Log.w("Bitmap", e);
    }
    return bitmap;
}

From source file:com.cssweb.android.view.FTrendView.java

public void reCycle() {
    paint = null;
    System.gc();
}

From source file:com.github.hexocraft.worldrestorer.WorldRestorerApi.java

private static boolean saveWorld(World world) {
    // Try to save all chunks
    final Chunk[] chunks = world.getLoadedChunks();
    for (final Chunk chunk : chunks)
        NmsWorldUtil.saveChunk(world, chunk);

    // Time reference
    long reference = new Date().getTime();

    // Save the world
    world.save();/*  w  w  w  . ja  v  a2 s . com*/

    // Wait for world to save
    try {
        long delay = 100, count = 0;
        while (count < 100) {
            long lastModify = new File(world.getWorldFolder(), "level.dat").lastModified();

            // Wait for the file to close
            if (lastModify - reference > 0) {
                Thread.sleep(800);
                return true;
            }

            // Wait again
            Thread.sleep(delay);

            // D'ont wait to much
            count++;
        }
    } catch (InterruptedException ex) {
        Thread.currentThread().interrupt();
    }

    System.runFinalization();
    System.gc();

    return false;
}