public void addAdjustedSelection(
     final Object element, Condition isExpired, @Nullable Object adjustmentCause) {
   myAdjustedSelection.put(element, isExpired);
   if (adjustmentCause != null) {
     myAdjustmentCause2Adjustment.put(adjustmentCause, element);
   }
 }
Пример #2
0
 /**
  * Method registerElementById
  *
  * @param element
  * @param idValue
  */
 public static void registerElementById(Element element, String idValue) {
   Document doc = element.getOwnerDocument();
   WeakHashMap elementMap = (WeakHashMap) docMap.get(doc);
   if (elementMap == null) {
     elementMap = new WeakHashMap();
     docMap.put(doc, elementMap);
   }
   elementMap.put(idValue, new WeakReference(element));
 }
Пример #3
0
 /** 測試WeakHashMapTest類,WeakHashMap的Key只保留了對實際對象的弱引用 */
 public static void main(String[] args) {
   WeakHashMap<String, String> whm = new WeakHashMap<String, String>();
   whm.put(new String("語文"), new String("良好"));
   whm.put(new String("數學"), new String("優秀"));
   whm.put(new String("英語"), new String("一般"));
   System.out.println("執行GC前whm:" + whm);
   // 直接使用String為強指針,下面無法回收
   whm.put("Java", "牛逼");
   Runtime.getRuntime().gc();
   Runtime.getRuntime().runFinalization();
   System.out.println("執行GC后whm:" + whm);
 }
Пример #4
0
  public static void makeEntity() throws Exception {
    Configuration cfg = getCfg();
    Template template = cfg.getTemplate("entity.html");

    // 生成文件设置
    String path =
        getJavaFileRoot() + File.separator + PropertyUtil.getValue("code.src.entity.root");
    mkdirs(path);
    path += File.separator + upperKey + "Entity.java";
    FileWriter sw = new FileWriter(new File(path));
    WeakHashMap<String, Object> data = new WeakHashMap<String, Object>();
    data.put("packageName", entityPackagePath);
    data.put("key", key);
    data.put("UpperKey", upperKey);
    data.put("ZhKey", zhKey);
    data.put("author", author);
    data.put("createDate", createDate);

    List<Field> list = MysqlUtil.getInstance().getTableField();
    noCommonFieldList = removeCommonFields(list);
    data.put("fieldList", list);
    data.put("noCommonFieldList", noCommonFieldList);

    primaryKey = MysqlUtil.getInstance().getPrimaryKey(list);
    fieldList = list;

    String level = PropertyUtil.getValue("created.code.level");
    if (!levels.contains(level)) {
      level = "all";
    }
    if ("all".equals(level) || "entity".equals(level)) {
      template.process(data, sw);
    }
  }
Пример #5
0
  public static void main(String[] args) {

    WeakHashMap<String, String> map = new WeakHashMap<String, String>();
    // 测试数据
    // 常量池对象不会回收
    map.put("abc", "a");
    map.put("d", "tets");
    // gc运行已被回收
    map.put(new String(""), "d");

    // 通知回收
    System.gc();
    System.runFinalization();
    System.out.println(map.size());
  }
Пример #6
0
 /**
  * Publish the description for this timeseries This is performed automatically at start of series
  * data publication, but subsequent changes to the description will not be published
  * automatically, and this method provides a means to send an update
  */
 public void publishDescription(IdentifiableTimeSeries identifiable) {
   SeriesDescriptionMessage d =
       udpMessageFactory.createTimeSeriesDescriptionMessage(
           identifiable.getPath(), identifiable.getDescription());
   seriesWithDescriptionsPublished.put(identifiable, null);
   safelyAddToQueue(d);
 }
 private Drawable getActivityIconWithCache(ComponentName componentname)
 {
     String s = componentname.flattenToShortString();
     if (mOutsideDrawablesCache.containsKey(s))
     {
         componentname = (android.graphics.drawable.Drawable.ConstantState)mOutsideDrawablesCache.get(s);
         if (componentname == null)
         {
             return null;
         } else
         {
             return componentname.newDrawable(mProviderContext.getResources());
         }
     }
     Drawable drawable = getActivityIcon(componentname);
     if (drawable == null)
     {
         componentname = null;
     } else
     {
         componentname = drawable.getConstantState();
     }
     mOutsideDrawablesCache.put(s, componentname);
     return drawable;
 }
Пример #8
0
  /**
   * When called it will traverse all visible leaves in the browseTree and collapse them if they
   * have been open for too long and are not selected.
   */
  private void collapseOldNodes() {
    Stack<ListableEntry> toConsider =
        new Stack<
            ListableEntry>(); // this is a stack of expanded nodes that need their children (and
                              // themselves) to be considered.
    toConsider.push(fs.getBrowseRoot()); // we know these are always expanded, and uncollapsable.
    toConsider.push(fs.getSearchRoot()); // "               "                    "

    // a) mark all uncollapsable nodes
    TreePath[] selecteds = browseTree.getSelectionPaths();
    if (selecteds != null) {
      for (TreePath selected : selecteds) {
        for (Object toMark :
            selected.getPath()) { // a selected nodes and their ancestors are not collapsable.
          expandedTimes.put(toMark, System.currentTimeMillis());
        }
      }
    }

    // b) collapse old expanded nodes.
    while (!toConsider.empty()) {
      for (FileSystemEntry child : toConsider.pop().getAllChildren()) {
        if (browseTree.isExpanded(child.getPath())) {
          toConsider.push(child);
          if (System.currentTimeMillis() - expandedTimes.get(child)
              > FS2Constants.CLIENT_BROWSETREE_COLLAPSE_INTERVAL) {
            browseTree.collapsePath(child.getPath());
            expandedTimes.remove(child);
          }
        }
      }
    }
  }
Пример #9
0
 /**
  * Entry point for instrumentation, invoked by the modified classloader for JVM <= 1.4x. For Java
  * 1.5 it is invoked by the agent interface of the JVM. Thus this method is invoked for each class
  * being loaded by the JVM. This does not imply that all classes are instrumented.
  *
  * @param loader the class loader attempting to load this class.
  * @param className class name of class being loaded
  * @param protectionDomain security protection domain
  * @param classfileBuffer
  * @param offset
  * @param length
  * @return null if the class is not instrumented (modified)
  */
 public static byte[] transform(
     ClassLoader loader,
     String className,
     ProtectionDomain protectionDomain,
     byte[] classfileBuffer,
     int offset,
     int length) {
   try {
     init();
     // Check to see if we already know this class loader or add it to the Javassist ClassPool
     // search path if
     // it's new. This is important in J2EE- and Servlet containers that have class loader
     // hierarchies
     if (!classLoaders.containsKey(
         loader)) { // <<< TODO: this is a weak hash map, will this really work as intended?
       classPool.insertClassPath(new LoaderClassPath(loader));
       classLoaders.put(loader, null);
     }
     // Parses the byte array into a CtClass instance.
     CtClass ctc = loadClass(classfileBuffer, offset, length);
     // transforms the class if it is of any interest to us.
     byte[] bb = findTypeAndTransform(ctc);
     // removes the CtClass from the pool to release memory
     ctc.detach();
     return bb;
   } catch (Throwable t) {
     Log.warning(
         "Exception during categorizeAndTransform of class "
             + className
             + ". The class will be ignored.",
         t);
     return null;
   }
 }
Пример #10
0
 /** @return the identifier for the page form */
 protected String registerPageForm(IPage p, IForm f) {
   String id = createUniqueIdForPage(p, f);
   m_formToIdentifierMap.put(f, id);
   f.removeFormListener(m_formListener);
   f.addFormListener(m_formListener);
   return id;
 }
  /**
   * @param key
   * @throws SQLException if the connection could not be created.
   * @see org.apache.commons.pool.KeyedPoolableObjectFactory#makeObject(java.lang.Object)
   */
  public synchronized Object makeObject(Object key) throws Exception {
    Object obj = null;
    UserPassKey upkey = (UserPassKey) key;

    PooledConnection pc = null;
    String username = upkey.getUsername();
    String password = upkey.getPassword();
    if (username == null) {
      pc = _cpds.getPooledConnection();
    } else {
      pc = _cpds.getPooledConnection(username, password);
    }

    if (pc == null) {
      throw new IllegalStateException(
          "Connection pool data source returned null from getPooledConnection");
    }

    // should we add this object as a listener or the pool.
    // consider the validateObject method in decision
    pc.addConnectionEventListener(this);
    obj = new PooledConnectionAndInfo(pc, username, password);
    pcMap.put(pc, obj);
    cleanupListeners();

    return obj;
  }
Пример #12
0
  public CompilerAssert(
      boolean incremental,
      ReadWriteFileSystem<I> sourcePath,
      ReadWriteFileSystem<O> sourceOutput,
      ReadWriteFileSystem<O> classOutput) {
    ClassLoader baseClassLoader = Thread.currentThread().getContextClassLoader();

    //
    ClassLoaderFileSystem classPath = classPathCache.get(baseClassLoader);
    if (classPath == null) {
      try {
        classPathCache.put(baseClassLoader, classPath = new ClassLoaderFileSystem(baseClassLoader));
      } catch (IOException e) {
        throw AbstractTestCase.failure(e);
      }
    }

    //
    this.strategy =
        incremental
            ? new CompileStrategy.Incremental<I, O>(
                classPath, sourcePath, sourceOutput, classOutput, META_MODEL_PROCESSOR_FACTORY)
            : new CompileStrategy.Batch<I, O>(
                classPath, sourcePath, sourceOutput, classOutput, META_MODEL_PROCESSOR_FACTORY);

    //
    this.baseClassLoader = baseClassLoader;
  }
Пример #13
0
  void updateSlot(final USK origUSK, final long number, final ClientContext context) {
    if (logMINOR) Logger.minor(this, "Updating (slot) " + origUSK.getURI() + " : " + number);
    USK clear = origUSK.clearCopy();
    final USKCallback[] callbacks;
    synchronized (this) {
      Long l = latestSlotByClearUSK.get(clear);
      if (logMINOR) Logger.minor(this, "Old slot: " + l);
      if ((l == null) || (number > l.longValue())) {
        l = Long.valueOf(number);
        latestSlotByClearUSK.put(clear, l);
        if (logMINOR) Logger.minor(this, "Put " + number);
      } else return;

      callbacks = subscribersByClearUSK.get(clear);
      if (temporaryBackgroundFetchersPrefetch.containsKey(clear)) {
        temporaryBackgroundFetchersPrefetch.put(clear, System.currentTimeMillis());
        schedulePrefetchChecker();
      }
    }
    if (callbacks != null) {
      // Run off-thread, because of locking, and because client callbacks may take some time
      final USK usk = origUSK.copy(number);
      for (final USKCallback callback : callbacks)
        context.mainExecutor.execute(
            new Runnable() {
              @Override
              public void run() {
                callback.onFoundEdition(
                    number, usk, null, // non-persistent
                    context, false, (short) -1, null, false, false);
              }
            },
            "USKManager callback executor for " + callback);
    }
  }
Пример #14
0
  public void add(Object object) {
    // if (objects.containsKey (object)) return;

    // S ystem.out.println("add " + ((AbstractVariable) object).getVariableName () + " : " +
    // object);
    objects.put(object, null);
  }
Пример #15
0
 /**
  * Retrieve an AuthorList for the given string of authors or editors.
  *
  * <p>This function tries to cache AuthorLists by string passed in.
  *
  * @param authors The string of authors or editors in bibtex format to parse.
  * @return An AuthorList object representing the given authors.
  */
 public static AuthorList getAuthorList(String authors) {
   AuthorList authorList = AUTHOR_CACHE.get(authors);
   if (authorList == null) {
     authorList = new AuthorList(authors);
     AUTHOR_CACHE.put(authors, authorList);
   }
   return authorList;
 }
Пример #16
0
	@Override
	protected void configureNewInstance(Instance instance) {
		super.configureNewInstance(instance);
		MemContents contents = getMemContents(instance);
		MemListener listener = new MemListener(instance);
		memListeners.put(instance, listener);
		contents.addHexModelListener(listener);
	}
 /**
  * @param file The name of the type face asset.
  * @param context The {@link Context} to use.
  * @return A new type face.
  */
 public Typeface getTypeface(final String file, final Context context) {
   Typeface result = MAP.get(file);
   if (result == null) {
     result = Typeface.createFromAsset(context.getAssets(), file);
     MAP.put(file, result);
   }
   return result;
 }
Пример #18
0
 public static AnimatorProxy wrap(View view) {
   AnimatorProxy proxy = PROXIES.get(view);
   if (proxy == null) {
     proxy = new AnimatorProxy(view);
     PROXIES.put(view, proxy);
   }
   return proxy;
 }
Пример #19
0
 public MPSLanguageVirtualFile getFileFor(@NotNull final Language language) {
   if (myVirtualFiles.containsKey(language)) {
     return myVirtualFiles.get(language);
   }
   MPSLanguageVirtualFile vf = new MPSLanguageVirtualFile(language);
   myVirtualFiles.put(language, vf);
   return vf;
 }
Пример #20
0
 /** Get thread status and create one if specified. */
 private synchronized ThreadStatus getOrCreateThreadStatus(Thread t) {
   ThreadStatus status = mThreadStatus.get(t);
   if (status == null) {
     status = new ThreadStatus();
     mThreadStatus.put(t, status);
   }
   return status;
 }
 @Nonnull
 public COLLTYPE getOrCreate(@Nullable final KEYTYPE aKey) {
   COLLTYPE aCont = get(aKey);
   if (aCont == null) {
     aCont = createNewCollection();
     super.put(aKey, aCont);
   }
   return aCont;
 }
 private Environment getEnvironment(Appendable writer) throws TemplateException, IOException {
   Environment environment = environments.get(writer);
   if (environment == null) {
     Map<String, Object> input = UtilMisc.toMap("key", null);
     environment = FreeMarkerWorker.renderTemplate(macroLibrary, input, writer);
     environments.put(writer, environment);
   }
   return environment;
 }
Пример #23
0
  private synchronized ThreadStatus getOrCreateThreadStatus(Thread thread) {
    ThreadStatus threadStatus = mThreadStatus.get(thread);
    if (threadStatus == null) {
      threadStatus = new ThreadStatus();
      mThreadStatus.put(thread, threadStatus);
    }

    return threadStatus;
  }
 public V get() throws Error {
   ClassLoader tccl = getContextClassLoader();
   V instance = CACHE.get(tccl);
   if (instance == null) {
     instance = createNewInstance();
     CACHE.put(tccl, instance);
   }
   return instance;
 }
 public static synchronized Applet2DragContext getDragContext(Plugin2Manager paramPlugin2Manager) {
   Applet2DragContext localApplet2DragContext =
       (Applet2DragContext) store.get(paramPlugin2Manager);
   if (null == localApplet2DragContext) {
     localApplet2DragContext = new Applet2DragContext(paramPlugin2Manager);
     store.put(paramPlugin2Manager, localApplet2DragContext);
   }
   return localApplet2DragContext;
 }
Пример #26
0
 /**
  * store a class with his methods
  *
  * @param clazz
  * @return returns stored Struct
  */
 private StructImpl store(Class clazz) {
   Field[] fieldsArr = clazz.getFields();
   StructImpl fieldsMap = new StructImpl();
   for (int i = 0; i < fieldsArr.length; i++) {
     storeField(fieldsArr[i], fieldsMap);
   }
   map.put(clazz, fieldsMap);
   return fieldsMap;
 }
Пример #27
0
  /**
   * Opens a cursor for a given database, dup'ing an existing CDB cursor if one is open for the
   * current thread.
   */
  Cursor openCursor(Database db, CursorConfig cursorConfig, boolean writeCursor, Transaction txn)
      throws DatabaseException {

    if (cdbMode) {
      CdbCursors cdbCursors = null;
      WeakHashMap cdbCursorsMap = (WeakHashMap) localCdbCursors.get();
      if (cdbCursorsMap == null) {
        cdbCursorsMap = new WeakHashMap();
        localCdbCursors.set(cdbCursorsMap);
      } else {
        cdbCursors = (CdbCursors) cdbCursorsMap.get(db);
      }
      if (cdbCursors == null) {
        cdbCursors = new CdbCursors();
        cdbCursorsMap.put(db, cdbCursors);
      }

      /*
       * In CDB mode the cursorConfig specified by the user is ignored
       * and only the writeCursor parameter is honored.  This is the only
       * meaningful cursor attribute for CDB, and here we count on
       * writeCursor flag being set correctly by the caller.
       */
      List cursors;
      CursorConfig cdbConfig;
      if (writeCursor) {
        if (cdbCursors.readCursors.size() > 0) {

          /*
           * Although CDB allows opening a write cursor when a read
           * cursor is open, a self-deadlock will occur if a write is
           * attempted for a record that is read-locked; we should
           * avoid self-deadlocks at all costs
           */
          throw new IllegalStateException("cannot open CDB write cursor when read cursor is open");
        }
        cursors = cdbCursors.writeCursors;
        cdbConfig = new CursorConfig();
        DbCompat.setWriteCursor(cdbConfig, true);
      } else {
        cursors = cdbCursors.readCursors;
        cdbConfig = null;
      }
      Cursor cursor;
      if (cursors.size() > 0) {
        Cursor other = ((Cursor) cursors.get(0));
        cursor = other.dup(false);
      } else {
        cursor = db.openCursor(null, cdbConfig);
      }
      cursors.add(cursor);
      return cursor;
    } else {
      return db.openCursor(txn, cursorConfig);
    }
  }
Пример #28
0
 public void filter(InterceptorChain chain) throws Throwable {
   LazyStatus stat = status.get(chain.getCallingObj());
   if (stat == null) {
     if (!chain.getCallingMethod().equals(setter)) {
       dao.fetchLinks(chain.getCallingObj(), fieldName); // 这里会触发setter被调用
     }
     status.put(chain.getCallingObj(), LazyStatus.NO_NEED); // 如果setter被调用,那么也就不再需要懒加载了
   }
   chain.doChain();
 }
Пример #29
0
 /**
  * @return the identifier for the page table or <code>null</code> if the table does not have a
  *     column filter manager.
  */
 protected String registerPageTable(IPage p, ITable t) {
   if (t.getColumnFilterManager() == null) {
     return null;
   }
   String id = createUniqueIdForPage(p, t);
   m_tableToIdentifierMap.put(t, id);
   t.getColumnFilterManager().removeListener(m_tableColumnFilterListener);
   t.getColumnFilterManager().addListener(m_tableColumnFilterListener);
   return id;
 }
Пример #30
0
 /**
  * Create a proxy to allow for modifying post-3.0 view properties on all pre-3.0 platforms.
  * <strong>DO NOT</strong> wrap your views if you are using {@code ObjectAnimator} as it will
  * handle that itself.
  *
  * @param view View to wrap.
  * @return Proxy to post-3.0 properties.
  */
 public static AnimatorProxy wrap(View view) {
   AnimatorProxy proxy = PROXIES.get(view);
   // This checks if the proxy already exists and whether it still is the animation of the given
   // view
   if (proxy == null || proxy != view.getAnimation()) {
     proxy = new AnimatorProxy(view);
     PROXIES.put(view, proxy);
   }
   return proxy;
 }