예제 #1
0
 private static void unloadPlugin(String name) {
   loadedPlugins.get(name).unload();
   loadedPlugins.remove(name);
   System.gc();
   System.gc();
   System.gc();
 }
예제 #2
0
  synchronized void openBookInternal(Book book, Bookmark bookmark) {
    if (book == null) {
      book = Library.Instance().getRecentBook();
      if (book == null || !book.File.exists()) {
        book = Book.getByFile(Library.getHelpFile());
      }
      if (book == null) {
        return;
      }
    }
    if (Model != null) {
      if (bookmark == null & book.File.getPath().equals(Model.Book.File.getPath())) {
        return;
      }
    }

    if (book != null) {
      onViewChanged();

      if (Model != null) {
        Model.Book.storePosition(BookTextView.getStartCursor());
      }
      BookTextView.setModel(null);
      FootnoteView.setModel(null);
      clearTextCaches();

      Model = null;
      System.gc();
      System.gc();
      try {
        Model = BookModel.createModel(book);
        ZLTextHyphenator.Instance().load(book.getLanguage());
        BookTextView.setModel(Model.getTextModel());
        BookTextView.gotoPosition(book.getStoredPosition());
        if (bookmark == null) {
          setView(BookTextView);
        } else {
          gotoBookmark(bookmark);
        }
        Library.Instance().addBookToRecentList(book);
        final StringBuilder title = new StringBuilder(book.getTitle());
        if (!book.authors().isEmpty()) {
          boolean first = true;
          for (Author a : book.authors()) {
            title.append(first ? " (" : ", ");
            title.append(a.DisplayName);
            first = false;
          }
          title.append(")");
        }
        setTitle(title.toString());
      } catch (BookReadingException e) {
        processException(e);
      }
    }
    getViewWidget().reset();
    getViewWidget().repaint();
  }
    @Override
    protected Product doInBackground(com.bc.ceres.core.ProgressMonitor pm) throws Exception {
      final TargetProductSelectorModel model = getTargetProductSelector().getModel();
      pm.beginTask("Writing...", model.isOpenInAppSelected() ? 100 : 95);
      ProgressMonitorList.instance().add(pm); // NESTMOD
      saveTime = 0L;
      Product product = null;
      try {
        // free cache	// NESTMOD
        JAI.getDefaultInstance().getTileCache().flush();
        System.gc();

        executeStartTime = Calendar.getInstance().getTime();
        long t0 = System.currentTimeMillis();
        Operator operator = null;
        if (targetProduct.getProductReader() instanceof OperatorProductReader) {
          final OperatorProductReader opReader =
              (OperatorProductReader) targetProduct.getProductReader();
          if (opReader.getOperatorContext().getOperator() instanceof Output) {
            operator = opReader.getOperatorContext().getOperator();
          }
        }
        if (operator == null) {
          WriteOp writeOp =
              new WriteOp(targetProduct, model.getProductFile(), model.getFormatName());
          writeOp.setDeleteOutputOnFailure(true);
          writeOp.setWriteEntireTileRows(true);
          writeOp.setClearCacheAfterRowWrite(false);
          operator = writeOp;
        }
        final OperatorExecutor executor = OperatorExecutor.create(operator);
        executor.execute(SubProgressMonitor.create(pm, 95));

        saveTime = System.currentTimeMillis() - t0;
        File targetFile = model.getProductFile();
        if (model.isOpenInAppSelected() && targetFile.exists()) {
          product = ProductIO.readProduct(targetFile);
          if (product == null) {
            product = targetProduct; // todo - check - this cannot be ok!!! (nf)
          }
          pm.worked(5);
        }
      } finally {
        // free cache
        JAI.getDefaultInstance().getTileCache().flush();
        System.gc();

        pm.done();
        ProgressMonitorList.instance().remove(pm); // NESTMOD
        if (product != targetProduct) {
          targetProduct.dispose();
        }
      }
      return product;
    }
예제 #4
0
  static void compare(Charset cs1, Charset cs2, char[] cc) throws Exception {
    System.gc(); // enqueue finalizable objects
    Thread.sleep(1000);
    System.gc(); // enqueue finalizable objects

    String csn1 = cs1.name();
    String csn2 = cs2.name();
    System.out.printf("Diff     <%s> <%s>...%n", csn1, csn2);

    Time t1 = new Time();
    Time t2 = new Time();

    byte[] bb1 = encode(cc, cs1, false, t1);
    byte[] bb2 = encode(cc, cs2, false, t2);

    System.out.printf(
        "    Encoding TimeRatio %s/%s: %d,%d :%f%n",
        csn2, csn1, t2.t, t1.t, (double) (t2.t) / (t1.t));
    if (!Arrays.equals(bb1, bb2)) {
      System.out.printf("        encoding failed%n");
    }

    char[] cc2 = decode(bb1, cs2, false, t2);
    char[] cc1 = decode(bb1, cs1, false, t1);
    System.out.printf(
        "    Decoding TimeRatio %s/%s: %d,%d :%f%n",
        csn2, csn1, t2.t, t1.t, (double) (t2.t) / (t1.t));
    if (!Arrays.equals(cc1, cc2)) {
      System.out.printf("        decoding failed%n");
    }

    bb1 = encode(cc, cs1, true, t1);
    bb2 = encode(cc, cs2, true, t2);

    System.out.printf(
        "    Encoding(dir) TimeRatio %s/%s: %d,%d :%f%n",
        csn2, csn1, t2.t, t1.t, (double) (t2.t) / (t1.t));

    if (!Arrays.equals(bb1, bb2)) System.out.printf("        encoding (direct) failed%n");

    cc1 = decode(bb1, cs1, true, t1);
    cc2 = decode(bb1, cs2, true, t2);
    System.out.printf(
        "    Decoding(dir) TimeRatio %s/%s: %d,%d :%f%n",
        csn2, csn1, t2.t, t1.t, (double) (t2.t) / (t1.t));
    if (!Arrays.equals(cc1, cc2)) {
      System.out.printf("        decoding (direct) failed%n");
    }
  }
예제 #5
0
 /** @brief Check if it's time to save the auctions out yet. */
 private void checkSnapshot() {
   if ((mLastCheckpointed + mCheckpointFrequency) < System.currentTimeMillis()) {
     mLastCheckpointed = System.currentTimeMillis();
     saveAuctions();
     System.gc();
   }
 }
예제 #6
0
  /**
   * This method is the main function of the thread of the collective. It does housekeeping and
   * regularly talks to peers to exchange information. It can be stopped by calling <code>close()
   * </code>.
   *
   * @see #close()
   */
  public final void run() {

    while (shouldLive) {
      // try{
      System.gc();
      removeOldStuff();
      if (!refresh()) {
        Address[] a = observer.getPeerAddresses();
        if (a != null)
          synchronized (cache) {
            for (int i = 0; i < a.length; ++i)
              cache.put(a[i].name, new ContributionBox(a[i], null));
          }
      }
      for (int i = 0; i < REFRESHRATE; i += 1000) {
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          shouldLive = false;
        }
        if (shouldLive == false) break;
        Thread.yield();
      }
      /*}
      catch( RuntimeException e )
      {
      	Logger.error( "Collective#run()",
      	"Runtime exception caught, something is going wrong",e);

      }*/
    }

    cache = null;
    observer = null;
  }
예제 #7
0
  /** Disposes of image memory and associated objects. */
  public void disposeLocal() {
    m_aafBox = null;
    m_aafM = null;

    m_afShear = null;
    m_afOffset = null;
    m_afA = null;
    m_afB = null;
    m_aiSliceBound = null;
    m_aiBound = null;

    m_aiSliceMin = null;
    m_aiSliceMax = null;
    m_aiClipMin = null;
    m_aiClipMax = null;

    m_aaaasEncode = null;
    m_aaasVolumeEncode = null;
    m_aasSliceEncode = null;

    m_aaiIndex = null;
    m_asSkip = null;
    m_aiCurrentI = null;

    m_aiInterC = null;

    m_kP00 = null;
    m_kP01 = null;
    m_kP10 = null;
    m_kP11 = null;
    m_kPosition = null;

    super.disposeLocal();
    System.gc();
  }
 static void runBenchmark(
     Client client,
     int maxIter,
     Results results,
     List<Entry<String, RequestInfo>> nativeSearchRequests,
     int minTerms,
     int warmerIter)
     throws IOException {
   int counter = 0;
   for (Entry<String, RequestInfo> entry : nativeSearchRequests) {
     SearchResponse searchResponse = null;
     // warm up
     for (int i = 0; i < warmerIter; i++) {
       searchResponse = client.search(entry.getValue().request).actionGet();
     }
     System.gc();
     // run benchmark
     StopWatch stopWatch = new StopWatch();
     stopWatch.start();
     for (int i = 0; i < maxIter; i++) {
       searchResponse = client.search(entry.getValue().request).actionGet();
     }
     stopWatch.stop();
     results.set(
         searchResponse, stopWatch, entry.getKey(), maxIter, counter, entry.getValue().numTerms);
     counter++;
   }
   results.printResults(null);
 }
예제 #9
0
  private void generateRules(ArrayList<Itemset> Lk, int clas) {
    int i, uncover;
    Itemset itemset;
    double confidence[] = new double[2];
    double var1[] = new double[2];
    double var2[] = new double[2];

    for (i = Lk.size() - 1; i >= 0; i--) {
      itemset = Lk.get(i);
      var2 = itemset.getSupport();
      if (var2[0] > 0.0) {
        var1 = itemset.getSupportClass();
        confidence[0] = var1[0] / var2[0];
        confidence[1] = var1[1] / var2[1];
      } else {
        confidence[0] = confidence[1] = 0.0;
      }
      if (confidence[0] > 0.4) {
        this.ruleBaseClase.add(itemset);
        ruleStage1++;
      }
      if (confidence[0] > this.minconf) Lk.remove(i);
    }

    if (this.ruleBaseClase.size() > 500000) {
      this.ruleBaseClase.reduceRules(clas);
      // System.out.println("Number of rules: " + this.ruleBase.size());
      System.gc();
    }
  }
  private void resolveClasspath() throws MojoExecutionException {
    parsePatchArtifacts();

    getLog()
        .info(
            "Resolving dependencies"
                + (useTransitives
                    ? ""
                    : " - warning! we are not using transitive dependencies, only those directly in the pom.xml"));

    resolvedArtifacts = collectAllProjectArtifacts();

    /*
     * Remove any Grails plugins that may be in the resolved artifact set.  This is because we
     * do not need them on the classpath, as they will be handled later on by a separate call to
     * "install" them.
     */
    pluginArtifacts = removePluginArtifacts(resolvedArtifacts);

    pluginDirectories = new ArrayList<File>();

    for (Artifact artifact : pluginArtifacts)
      pluginDirectories.add(getPluginDirAndInstallIfNecessary(artifact));

    if (getLog().isInfoEnabled()) {
      for (File f : pluginDirectories) {
        getLog().info("plugin: " + f.getAbsolutePath());
      }
    }

    classpath = generateGrailsExecutionClasspath(resolvedArtifacts);

    System.gc();
  }
예제 #11
0
 /** low-level test for critical performance issue described in bug [3078236] */
 public void testExceptionChaining() throws SQLException {
   for (boolean warn : new boolean[] {false, true}) {
     long base = 0;
     for (int size : new int[] {10, 25, 50, 100, 500}) {
       SQLDiagnostic diag = new SQLDiagnostic(0);
       System.gc();
       long start = System.nanoTime();
       for (int c = 0; c < size * 1000; c++) {
         if (warn) {
           diag.addWarning(new SQLWarning());
         } else {
           diag.addException(new SQLException());
         }
       }
       long avg = (System.nanoTime() - start) / size; // nanoseconds per 1000 exceptions
       // ensure time grows linear (allows factor 2 deviation, but not exponential effects)
       assertTrue(
           "chaining "
               + size * 1000
               + (warn ? " warnings" : " exceptions")
               + " slowed down too much ("
               + base / 1000000
               + " ms -> "
               + avg / 1000000
               + " ms per 1000)",
           base == 0 || avg < base * 2);
       base = base == 0 ? avg : base;
     }
   }
 }
예제 #12
0
  public void generateRB() {
    int i, j, uncover;

    ruleStage1 = 0;

    this.ruleBaseClase =
        new RuleBase(
            this.dataBase,
            this.train,
            this.test,
            this.ruleBase.getK(),
            this.ruleBase.getTypeInference());

    for (i = 0; i < this.nClasses; i++) {
      this.minsup = minSupps[i];
      this.generateL2(i);
      this.generateLarge(this.L2, i);

      this.ruleBaseClase.reduceRules(i);

      this.ruleBase.add(this.ruleBaseClase);
      this.ruleBaseClase.clear();
      System.gc();
    }
  }
예제 #13
0
  private void generateLarge(ArrayList<Itemset> Lk, int clas) {
    int i, j, size;
    ArrayList<Itemset> Lnew;
    Itemset newItemset, itemseti, itemsetj;

    size = Lk.size();

    if (size > 1) {
      if (((Lk.get(0)).size() < this.nVariables) && ((Lk.get(0)).size() < this.depth)) {
        Lnew = new ArrayList<Itemset>();

        for (i = 0; i < size - 1; i++) {
          itemseti = Lk.get(i);
          for (j = i + 1; j < size; j++) {
            itemsetj = Lk.get(j);
            if (this.isCombinable(itemseti, itemsetj)) {
              newItemset = itemseti.clone();
              newItemset.add((itemsetj.get(itemsetj.size() - 1)).clone());
              newItemset.calculateSupports(this.dataBase, this.train);
              if (newItemset.getSupportClass()[0] >= this.minsup) Lnew.add(newItemset);
            }
          }

          this.generateRules(Lnew, clas);
          this.generateLarge(Lnew, clas);
          Lnew.clear();
          System.gc();
        }
      }
    }
  }
예제 #14
0
파일: GA.java 프로젝트: JamesEarle/GPP
  /**
   * Run the main GP run loop until the generation limit it met, or until the provided number of
   * generations has elapsed.
   *
   * @param inGenerations The maximum number of generations to run during this call. This is
   *     distinct from the hard generation limit which determines when the GA is actually complete.
   * @return true if the the execution of the GA is complete.
   */
  public boolean Run(int inGenerations) throws Exception {
    // inGenerations below must have !=, not >, since often inGenerations
    // is called at -1
    while (!Terminate() && inGenerations != 0) {
      BeginGeneration();

      Evaluate();
      Reproduce();

      EndGeneration();

      Print(Report());

      Checkpoint();

      System.gc();

      _currentPopulation = (_currentPopulation == 0 ? 1 : 0);
      _generationCount++;
      inGenerations--;
    }

    if (Terminate()) {
      // Since this value was changed after termination conditions were
      // set, revert back to previous state.
      _currentPopulation = (_currentPopulation == 0 ? 1 : 0);

      Print(FinalReport());
    }

    return (_generationCount < _maxGenerations);
  }
예제 #15
0
  public int clearDeleted() {
    int rval = DeletedEntry.clear();

    saveAuctions();
    System.gc();

    return rval;
  }
  /** Method declaration Adjust this method for large strings...ie multi megabtypes. */
  void execute() {

    String sCmd = null;

    if (4096 <= ifHuge.length()) {
      sCmd = ifHuge;
    } else {
      sCmd = txtCommand.getText();
    }

    if (sCmd.startsWith("-->>>TEST<<<--")) {
      testPerformance();

      return;
    }

    String g[] = new String[1];

    lTime = System.currentTimeMillis();

    try {
      sStatement.execute(sCmd);

      lTime = System.currentTimeMillis() - lTime;

      int r = sStatement.getUpdateCount();

      if (r == -1) {
        formatResultSet(sStatement.getResultSet());
      } else {
        g[0] = "update count";

        gResult.setHead(g);

        g[0] = String.valueOf(r);

        gResult.addRow(g);
      }

      addToRecent(txtCommand.getText());
    } catch (SQLException e) {
      lTime = System.currentTimeMillis() - lTime;
      g[0] = "SQL Error";

      gResult.setHead(g);

      String s = e.getMessage();

      s += " / Error Code: " + e.getErrorCode();
      s += " / State: " + e.getSQLState();
      g[0] = s;

      gResult.addRow(g);
    }

    updateResult();
    System.gc();
  }
 public static void assertTiming(
     String message, long expected, int attempts, @NotNull Runnable actionToMeasure) {
   while (true) {
     attempts--;
     long duration = measure(actionToMeasure);
     try {
       assertTiming(message, expected, duration);
       break;
     } catch (AssertionFailedError e) {
       if (attempts == 0) throw e;
       System.gc();
       System.gc();
       System.gc();
       String s = "Another epic fail (remaining attempts: " + attempts + "): " + e.getMessage();
       TeamCityLogger.warning(s, null);
       System.err.println(s);
     }
   }
 }
 public static void main(String[] args) throws Exception {
   MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
   final Boolean isNotificationSupported =
       AccessController.doPrivileged(
           new PrivilegedAction<Boolean>() {
             public Boolean run() {
               try {
                 Class cl = Class.forName("sun.management.VMManagementImpl");
                 Field f = cl.getDeclaredField("gcNotificationSupport");
                 f.setAccessible(true);
                 return f.getBoolean(null);
               } catch (ClassNotFoundException e) {
                 return false;
               } catch (NoSuchFieldException e) {
                 return false;
               } catch (IllegalAccessException e) {
                 return false;
               }
             }
           });
   if (!isNotificationSupported) {
     System.out.println("GC Notification not supported by the JVM, test skipped");
     return;
   }
   final ObjectName gcMXBeanPattern = new ObjectName("java.lang:type=GarbageCollector,*");
   Set<ObjectName> names = mbs.queryNames(gcMXBeanPattern, null);
   if (names.isEmpty()) throw new Exception("Test incorrect: no GC MXBeans");
   number = names.size();
   for (ObjectName n : names) {
     if (mbs.isInstanceOf(n, "javax.management.NotificationEmitter")) {
       listenerInvoked.put(n.getCanonicalName(), null);
       GcListener listener = new GcListener();
       mbs.addNotificationListener(n, listener, null, null);
     }
   }
   // Invocation of System.gc() to trigger major GC
   System.gc();
   // Allocation of many short living and small objects to trigger minor GC
   Object data[] = new Object[32];
   for (int i = 0; i < 100000000; i++) {
     data[i % 32] = new int[8];
   }
   int wakeup = 0;
   synchronized (synchronizer) {
     while (count != number) {
       synchronizer.wait(10000);
       wakeup++;
       if (wakeup > 10) break;
     }
   }
   for (GarbageCollectionNotificationInfo notif : listenerInvoked.values()) {
     checkGarbageCollectionNotificationInfoContent(notif);
   }
   System.out.println("Test passed");
 }
 public static void main(String[] args) {
   System.gc();
   // Schedule a job for the event-dispatching thread:
   // creating and showing this application's GUI.
   javax.swing.SwingUtilities.invokeLater(
       new Runnable() {
         public void run() {
           createAndShowGUI();
         }
       });
 } // end of main
  @Override
  @Nullable
  public Project newProject(
      final String projectName,
      @NotNull String filePath,
      boolean useDefaultProjectSettings,
      boolean isDummy) {
    filePath = toCanonicalName(filePath);

    //noinspection ConstantConditions
    if (LOG_PROJECT_LEAKAGE_IN_TESTS && ApplicationManager.getApplication().isUnitTestMode()) {
      for (int i = 0; i < 42; i++) {
        if (myProjects.size() < MAX_LEAKY_PROJECTS) break;
        System.gc();
        TimeoutUtil.sleep(100);
        System.gc();
      }

      if (myProjects.size() >= MAX_LEAKY_PROJECTS) {
        List<Project> copy = new ArrayList<Project>(myProjects.keySet());
        myProjects.clear();
        throw new TooManyProjectLeakedException(copy);
      }
    }

    ProjectImpl project =
        createProject(
            projectName, filePath, false, ApplicationManager.getApplication().isUnitTestMode());
    try {
      initProject(project, useDefaultProjectSettings ? (ProjectImpl) getDefaultProject() : null);
      if (LOG_PROJECT_LEAKAGE_IN_TESTS) {
        myProjects.put(project, null);
      }
      return project;
    } catch (final Exception e) {
      LOG.info(e);
      Messages.showErrorDialog(message(e), ProjectBundle.message("project.load.default.error"));
    }
    return null;
  }
  @After
  public void tearDown() throws InterruptedException {

    for (final Closeable closeable : new Closeable[] {map1, map2}) {
      try {
        closeable.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }

    System.gc();
  }
예제 #22
0
 public double memoryUse(Environmental E, int number) {
   double s = -1.0;
   try {
     int n = number;
     Object[] objs = new Object[n];
     Environmental cl = E;
     Runtime rt = Runtime.getRuntime();
     long m0 = rt.totalMemory() - rt.freeMemory();
     System.gc();
     Thread.sleep(500);
     for (int i = 0; i < n; ++i) objs[i] = E = (Environmental) cl.copyOf();
     System.gc();
     Thread.sleep(1000);
     long m1 = rt.totalMemory() - rt.freeMemory();
     long dm = m1 - m0;
     s = (double) dm / (double) n;
     if (s < 0.0) return memoryUse(E, number);
   } catch (Exception e) {
     return -1;
   }
   return s;
 }
예제 #23
0
 // To be called exactly twice by the child process
 public static void rendezvousChild() {
   try {
     for (int i = 0; i < 100; i++) {
       System.gc();
       System.runFinalization();
       Thread.sleep(50);
     }
     System.out.write((byte) '\n');
     System.out.flush();
     System.in.read();
   } catch (Throwable t) {
     throw new Error(t);
   }
 }
예제 #24
0
 public static void main(String[] args) {
   int size = 1000;
   // Or, choose size via the command line:
   if (args.length > 0) size = new Integer(args[0]);
   Key[] keys = new Key[size];
   WeakHashMap<Key, Value> map = new WeakHashMap<Key, Value>();
   for (int i = 0; i < size; i++) {
     Key k = new Key(Integer.toString(i));
     Value v = new Value(Integer.toString(i));
     if (i % 3 == 0) keys[i] = k; // Save as "real" references
     map.put(k, v);
   }
   System.gc();
 }
예제 #25
0
 private void shutDown() {
   try {
     try {
       Thread.sleep(2000);
     } catch (InterruptedException e) {
     }
     System.out.println("nulling reference");
     sipStack.deleteListeningPoint(tcpListeningPoint);
     sipStack.deleteListeningPoint(udpListeningPoint);
     // This will close down the stack and exit all threads
     tcpProvider.removeSipListener(this);
     udpProvider.removeSipListener(this);
     while (true) {
       try {
         sipStack.deleteSipProvider(udpProvider);
         sipStack.deleteSipProvider(tcpProvider);
         break;
       } catch (ObjectInUseException ex) {
         try {
           Thread.sleep(2000);
         } catch (InterruptedException e) {
           continue;
         }
       }
     }
     sipStack = null;
     tcpProvider = null;
     udpProvider = null;
     this.contactHeader = null;
     addressFactory = null;
     headerFactory = null;
     messageFactory = null;
     this.udpListeningPoint = null;
     this.tcpListeningPoint = null;
     this.reInviteCount = 0;
     System.gc();
     // Redo this from the start.
     if (counter < 10) this.init();
     else counter++;
   } catch (Exception ex) {
     ex.printStackTrace();
   }
 }
  /**
   * Calls garbage collector and wait.
   *
   * @throws Exception if any thread has interrupted the current thread while waiting.
   */
  private void gc() throws Exception {
    Runtime rt = Runtime.getRuntime();

    long freeMem0 = rt.freeMemory();
    long freeMem = Long.MAX_VALUE;

    int cnt = 0;

    while (freeMem0 < freeMem && cnt < GC_CALL_CNT) {
      System.gc();

      U.sleep(WAIT_TIME);

      cnt++;

      freeMem = freeMem0;
      freeMem0 = rt.freeMemory();
    }
  }
예제 #27
0
  /**
   * Called with a DjVuBean property has changed.
   *
   * @param e the PropertyChangeEvent.
   */
  public void propertyChange(final PropertyChangeEvent e) {
    try {
      final String name = e.getPropertyName();

      if ("page".equalsIgnoreCase(name)) {
        final Object object = e.getNewValue();

        if (object instanceof Number) {
          setCheckedPage(((Number) object).intValue() - 1);
        }
      } else if ("propertyName".equalsIgnoreCase(name)) {
        final String propertyName = (String) e.getNewValue();

        if ("navpane".equalsIgnoreCase(propertyName)) {
          setVisible("Outline".equalsIgnoreCase(djvuBean.properties.getProperty(propertyName)));
        }
      }
    } catch (final Throwable exp) {
      exp.printStackTrace(DjVuOptions.err);
      System.gc();
    }
  }
예제 #28
0
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    articleFeed = new ArticleFeed(this.getBaseContext());
    setFeed(articleFeed);

    articleFeed.loadCache();

    ThumbnailCache.getInstance().setContext(getBaseContext());

    setContentView(R.layout.articles_list);
    rubricsList = (LinearLayout) findViewById(R.id.articles_list);
    emptyMessage = (TextView) findViewById(R.id.empty);

    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    String fontSize = preferences.getString("font_list_size", "medium");

    float imageSize = 12;
    if (fontSize.equalsIgnoreCase("small")) {
      imageSize = getResources().getDimension(R.dimen.image_size_small);
    } else if (fontSize.equalsIgnoreCase("medium")) {
      imageSize = getResources().getDimension(R.dimen.image_size_medium);
    } else if (fontSize.equalsIgnoreCase("large")) {
      imageSize = getResources().getDimension(R.dimen.image_size_large);
    }

    Display display =
        ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
    int width = display.getWidth();

    int maxImageCount = (int) (width / imageSize + 1);
    Rubric.setDefaultViewCount(maxImageCount);
    System.gc();

    listArticlesViews = new LinkedList<View>();
    generateRubricsList();
  }
예제 #29
0
  /** Test program. */
  public static void main(String[] arg) throws Exception {
    Map cache = new SoftValuedHashMap();

    for (int i = 0, j = 0; i < 100000; i++, j += 15) {
      if (i % 100 == 0) {
        System.out.println("Size = " + cache.size());
      }

      // Thread.sleep(1);

      Integer key = new Integer(i);
      Integer value = new Integer(j);

      cache.put(key, value);
    }

    Map.Entry entry = (Map.Entry) cache.entrySet().iterator().next();
    System.out.println(entry);
    // entry = null;

    System.out.println(cache);

    int originalSize = cache.size();

    // cache = null;

    for (int i = 0; i < 100; i++) {
      System.gc();
    }

    System.out.println(cache);

    System.out.println(originalSize);
    System.out.println(cache.size());
    System.out.println(entry);

    Thread.sleep(1000000);
  }
 @Scheduled(fixedDelay = SCHEDULED_CHECK)
 public void checkActiveClients() {
   Set<String> users = user_vidNameMap.keySet();
   Iterator<String> it = users.iterator();
   long time = System.currentTimeMillis();
   int count = 0;
   while (it.hasNext()) {
     count++;
     String user = it.next();
     if (user == null) continue;
     if (userAliveMap.containsKey(user)) {
       if (userAliveMap.get(user).longValue() < time) {
         removeUser(user);
         userAliveMap.remove(user);
       }
     } else {
       throw new RuntimeException("user in user-vid map but not in user-alive map");
     }
   }
   // System.out.println("Debug: Scheduled Check count:"+count+" user
   // count:"+user_vidNameMap.size());
   System.gc();
 }