List of usage examples for java.lang.ref SoftReference SoftReference
public SoftReference(T referent)
From source file:jetbrains.exodus.env.EnvironmentImpl.java
private LongObjectCacheBase invalidateTreeNodesCache() { final int treeNodesCacheSize = ec.getTreeNodesCacheSize(); final LongObjectCacheBase result = treeNodesCacheSize == 0 ? null : new ConcurrentLongObjectCache(treeNodesCacheSize, 2); treeNodesCache = result == null ? null : new SoftReference<>(result); return result; }
From source file:com.silentcircle.contacts.ContactPhotoManager.java
/** * If necessary, decodes bytes stored in the holder to Bitmap. As long as the * bitmap is held either by {@link #mBitmapCache} or by a soft reference in * the holder, it will not be necessary to decode the bitmap. *///from ww w .j av a2s. c o m private static void inflateBitmap(BitmapHolder holder, int requestedExtent) { final int sampleSize = BitmapUtil.findOptimalSampleSize(holder.originalSmallerExtent, requestedExtent); byte[] bytes = holder.bytes; if (bytes == null || bytes.length == 0) { return; } if (sampleSize == holder.decodedSampleSize) { // Check the soft reference. If will be retained if the bitmap is also // in the LRU cache, so we don't need to check the LRU cache explicitly. if (holder.bitmapRef != null) { holder.bitmap = holder.bitmapRef.get(); if (holder.bitmap != null) { return; } } } try { Bitmap bitmap = BitmapUtil.decodeBitmapFromBytes(bytes, sampleSize); // make bitmap mutable and draw size onto it if (DEBUG_SIZES) { Bitmap original = bitmap; bitmap = bitmap.copy(bitmap.getConfig(), true); original.recycle(); Canvas canvas = new Canvas(bitmap); Paint paint = new Paint(); paint.setTextSize(16); paint.setColor(Color.BLUE); paint.setStyle(Style.FILL); canvas.drawRect(0.0f, 0.0f, 50.0f, 20.0f, paint); paint.setColor(Color.WHITE); paint.setAntiAlias(true); canvas.drawText(bitmap.getWidth() + "/" + sampleSize, 0, 15, paint); } holder.decodedSampleSize = sampleSize; holder.bitmap = bitmap; holder.bitmapRef = new SoftReference<Bitmap>(bitmap); if (DEBUG) { int bCount = (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR1) ? bitmap.getRowBytes() * bitmap.getHeight() : bitmap.getByteCount(); Log.d(TAG, "inflateBitmap " + btk(bytes.length) + " -> " + bitmap.getWidth() + "x" + bitmap.getHeight() + ", " + btk(bCount)); } } catch (OutOfMemoryError e) { // Do nothing - the photo will appear to be missing } }
From source file:edu.ksu.cis.santos.mdcf.dml.symbol.SymbolTable.java
/** * Retrieves all {@link RefinedType}s declared in the {@link #models}. * /*from w w w . j a v a2 s. c om*/ * @return an immutable {@link List}. */ public List<RefinedType> refinedTypes() { List<RefinedType> result = null; if ((this._refinedTypes == null) || ((result = this._refinedTypes.get()) == null)) { final ImmutableList.Builder<RefinedType> b = ImmutableList.builder(); new AbstractVisitor() { @Override public boolean visitRefinedType(final RefinedType node) { b.add(node); return true; } }.visit(this.models); result = b.build(); this._refinedTypes = new SoftReference<List<RefinedType>>(result); } return result; }
From source file:edu.ku.brc.specify.datamodel.WorkbenchRow.java
/** * Reads in the disciplines file (is loaded when the class is loaded). * @return Reads in the disciplines file (is loaded when the class is loaded). *//*from w ww.jav a 2s . com*/ @Transient public ImageIcon getFullSizeImage() { if (cardImageData != null && StringUtils.isNotEmpty(cardImageFullPath)) { ImageIcon fullSizeImage = null; if (fullSizeImageSR != null) { fullSizeImage = fullSizeImageSR.get(); } if (fullSizeImage == null) { try { ImageIcon iconImage = new ImageIcon(cardImageFullPath); fullSizeImageSR = new SoftReference<ImageIcon>(iconImage); } catch (java.lang.OutOfMemoryError memEx) { loadStatus = LoadStatus.OutOfMemory; loadException = new Exception("Out of Memory"); log.error(memEx); return null; } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(WorkbenchRow.class, ex); log.error(ex); loadStatus = LoadStatus.Error; loadException = ex; return null; } } return fullSizeImageSR.get(); } return null; }
From source file:com.silentcircle.contacts.ContactPhotoManager.java
@Override public void cacheBitmap(Uri photoUri, Bitmap bitmap, byte[] photoBytes) { final int smallerExtent = Math.min(bitmap.getWidth(), bitmap.getHeight()); // We can pretend here that the extent of the photo was the size that we originally // requested// w ww.ja va 2 s . c om Request request = Request.createFromUri(photoUri, smallerExtent, false, DEFAULT_AVATAR); BitmapHolder holder = new BitmapHolder(photoBytes, smallerExtent); holder.bitmapRef = new SoftReference<Bitmap>(bitmap); mBitmapHolderCache.put(request.getKey(), holder); mBitmapHolderCacheAllUnfresh = false; mBitmapCache.put(request.getKey(), bitmap); }
From source file:ch.rasc.extclassgenerator.ModelGenerator.java
public static String generateJavascript(ModelBean model, OutputConfig outputConfig) { if (!outputConfig.isDebug()) { JsCacheKey key = new JsCacheKey(model, outputConfig); SoftReference<String> jsReference = jsCache.get(key); if (jsReference != null && jsReference.get() != null) { return jsReference.get(); }/*from w ww . ja v a 2 s.c om*/ } ObjectMapper mapper = new ObjectMapper(); mapper.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, false); if (!outputConfig.isSurroundApiWithQuotes()) { if (outputConfig.getOutputFormat() == OutputFormat.EXTJS5) { mapper.addMixInAnnotations(ProxyObject.class, ProxyObjectWithoutApiQuotesExtJs5Mixin.class); } else { mapper.addMixInAnnotations(ProxyObject.class, ProxyObjectWithoutApiQuotesMixin.class); } mapper.addMixInAnnotations(ApiObject.class, ApiObjectMixin.class); } else { if (outputConfig.getOutputFormat() != OutputFormat.EXTJS5) { mapper.addMixInAnnotations(ProxyObject.class, ProxyObjectWithApiQuotesMixin.class); } } Map<String, Object> modelObject = new LinkedHashMap<String, Object>(); modelObject.put("extend", model.getExtend()); if (!model.getAssociations().isEmpty()) { Set<String> usesClasses = new HashSet<String>(); for (AbstractAssociation association : model.getAssociations()) { usesClasses.add(association.getModel()); } usesClasses.remove(model.getName()); if (!usesClasses.isEmpty()) { modelObject.put("uses", usesClasses); } } Map<String, Object> configObject = new LinkedHashMap<String, Object>(); ProxyObject proxyObject = new ProxyObject(model, outputConfig); Map<String, ModelFieldBean> fields = model.getFields(); Set<String> requires = new HashSet<String>(); if (!model.getValidations().isEmpty() && outputConfig.getOutputFormat() == OutputFormat.EXTJS5) { requires = addValidatorsToField(fields, model.getValidations()); } if (proxyObject.hasContent() && outputConfig.getOutputFormat() == OutputFormat.EXTJS5) { requires.add("Ext.data.proxy.Direct"); } if (StringUtils.hasText(model.getIdentifier()) && outputConfig.getOutputFormat() == OutputFormat.EXTJS5) { if ("sequential".equals(model.getIdentifier())) { requires.add("Ext.data.identifier.Sequential"); } else if ("uuid".equals(model.getIdentifier())) { requires.add("Ext.data.identifier.Uuid"); } else if ("negative".equals(model.getIdentifier())) { requires.add("Ext.data.identifier.Negative"); } } if (requires != null && !requires.isEmpty()) { configObject.put("requires", requires); } if (StringUtils.hasText(model.getIdentifier())) { if (outputConfig.getOutputFormat() == OutputFormat.EXTJS5 || outputConfig.getOutputFormat() == OutputFormat.TOUCH2) { configObject.put("identifier", model.getIdentifier()); } else { configObject.put("idgen", model.getIdentifier()); } } if (StringUtils.hasText(model.getIdProperty()) && !model.getIdProperty().equals("id")) { configObject.put("idProperty", model.getIdProperty()); } if (outputConfig.getOutputFormat() == OutputFormat.EXTJS5 && StringUtils.hasText(model.getVersionProperty())) { configObject.put("versionProperty", model.getVersionProperty()); } if (StringUtils.hasText(model.getClientIdProperty())) { if (outputConfig.getOutputFormat() == OutputFormat.EXTJS5 || outputConfig.getOutputFormat() == OutputFormat.EXTJS4) { configObject.put("clientIdProperty", model.getClientIdProperty()); } else if (outputConfig.getOutputFormat() == OutputFormat.TOUCH2 && !"clientId".equals(model.getClientIdProperty())) { configObject.put("clientIdProperty", model.getClientIdProperty()); } } for (ModelFieldBean field : fields.values()) { field.updateTypes(outputConfig); } List<Object> fieldConfigObjects = new ArrayList<Object>(); for (ModelFieldBean field : fields.values()) { if (field.hasOnlyName(outputConfig)) { fieldConfigObjects.add(field.getName()); } else { fieldConfigObjects.add(field); } } configObject.put("fields", fieldConfigObjects); if (!model.getAssociations().isEmpty()) { configObject.put("associations", model.getAssociations()); } if (!model.getValidations().isEmpty() && !(outputConfig.getOutputFormat() == OutputFormat.EXTJS5)) { configObject.put("validations", model.getValidations()); } if (proxyObject.hasContent()) { configObject.put("proxy", proxyObject); } if (outputConfig.getOutputFormat() == OutputFormat.EXTJS4 || outputConfig.getOutputFormat() == OutputFormat.EXTJS5) { modelObject.putAll(configObject); } else { modelObject.put("config", configObject); } StringBuilder sb = new StringBuilder(); sb.append("Ext.define(\"").append(model.getName()).append("\","); if (outputConfig.isDebug()) { sb.append("\n"); } String configObjectString; Class<?> jsonView = JsonViews.ExtJS4.class; if (outputConfig.getOutputFormat() == OutputFormat.TOUCH2) { jsonView = JsonViews.Touch2.class; } else if (outputConfig.getOutputFormat() == OutputFormat.EXTJS5) { jsonView = JsonViews.ExtJS5.class; } try { if (outputConfig.isDebug()) { configObjectString = mapper.writerWithDefaultPrettyPrinter().withView(jsonView) .writeValueAsString(modelObject); } else { configObjectString = mapper.writerWithView(jsonView).writeValueAsString(modelObject); } } catch (JsonGenerationException e) { throw new RuntimeException(e); } catch (JsonMappingException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } sb.append(configObjectString); sb.append(");"); String result = sb.toString(); if (outputConfig.isUseSingleQuotes()) { result = result.replace('"', '\''); } if (!outputConfig.isDebug()) { jsCache.put(new JsCacheKey(model, outputConfig), new SoftReference<String>(result)); } return result; }
From source file:edu.ksu.cis.santos.mdcf.dml.symbol.SymbolTable.java
/** * Retrieves a {@link Multimap} that relates a sub type's fully-qualified name * (either of {@link BasicType#name} or {@link Feature#name}) to its super * type's fully-qualified name (either of {@link BasicType#name} or * {@link Feature#name}).//from w w w . j a v a 2 s .c o m * * @return an immutable {@link Multimap}. */ public Multimap<String, String> superTransitiveMap() { Multimap<String, String> result = null; if ((this._superMap == null) || ((result = this._superMap.get()) == null)) { final HashSet<String> seen = new HashSet<>(); final HashMultimap<String, String> m = HashMultimap.create(); for (final BasicType bt : basicTypes()) { superTransitive(seen, m, bt); } for (final Feature f : features()) { superTransitive(seen, m, f); } final ImmutableMultimap.Builder<String, String> superb = ImmutableMultimap.builder(); final ImmutableMultimap.Builder<String, String> subb = ImmutableMultimap.builder(); for (final String sub : m.keySet()) { final Set<String> sups = m.get(sub); for (final String sup : sups) { superb.put(sub, sup); subb.put(sup, sub); } } result = superb.build(); this._superMap = new SoftReference<Multimap<String, String>>(result); this._subMap = new SoftReference<Multimap<String, String>>(subb.build()); } return result; }
From source file:net.yacy.http.servlets.YaCyDefaultServlet.java
protected Method rewriteMethod(final File classFile) throws InvocationTargetException { Method m = null;/*from w w w .j a v a2 s. c om*/ // 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 *///from ww w . j av 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.ibm.bi.dml.runtime.controlprogram.caching.MatrixObject.java
/** * NOTE: for reading matrix partitions, we could cache (in its real sense) the read block * with soft references (no need for eviction, as partitioning only applied for read-only matrices). * However, since we currently only support row- and column-wise partitioning caching is not applied yet. * This could be changed once we also support column-block-wise and row-block-wise. Furthermore, * as we reject to partition vectors and support only full row or column indexing, no metadata (apart from * the partition flag) is required. //from w ww . j a va 2 s.com * * @param pred * @return * @throws CacheException */ public synchronized MatrixBlock readMatrixPartition(IndexRange pred) throws CacheException { if (LOG.isTraceEnabled()) LOG.trace("Acquire partition " + _varName + " " + pred); long t0 = DMLScript.STATISTICS ? System.nanoTime() : 0; if (!_partitioned) throw new CacheStatusException("MatrixObject not available to indexed read."); //return static partition of set from outside of the program if (_partitionInMemory != null) return _partitionInMemory; MatrixBlock mb = null; try { boolean blockwise = (_partitionFormat == PDataPartitionFormat.ROW_BLOCK_WISE || _partitionFormat == PDataPartitionFormat.COLUMN_BLOCK_WISE); //preparations for block wise access MatrixFormatMetaData iimd = (MatrixFormatMetaData) _metaData; MatrixCharacteristics mc = iimd.getMatrixCharacteristics(); int brlen = mc.getRowsPerBlock(); int bclen = mc.getColsPerBlock(); //get filename depending on format String fname = getPartitionFileName(pred, brlen, bclen); //probe cache if (blockwise && _partitionCacheName != null && _partitionCacheName.equals(fname)) { mb = _cache.get(); //try getting block from cache } if (mb == null) //block not in cache { //get rows and cols long rows = -1; long cols = -1; switch (_partitionFormat) { case ROW_WISE: rows = 1; cols = mc.getCols(); break; case ROW_BLOCK_WISE: rows = brlen; cols = mc.getCols(); break; case COLUMN_WISE: rows = mc.getRows(); cols = 1; break; case COLUMN_BLOCK_WISE: rows = mc.getRows(); cols = bclen; break; default: throw new CacheException("Unsupported partition format: " + _partitionFormat); } //read the if (MapReduceTool.existsFileOnHDFS(fname)) mb = readMatrixFromHDFS(fname, rows, cols); else { mb = new MatrixBlock((int) rows, (int) cols, true); LOG.warn("Reading empty matrix partition " + fname); } } //post processing if (blockwise) { //put block into cache _partitionCacheName = fname; _cache = new SoftReference<MatrixBlock>(mb); if (_partitionFormat == PDataPartitionFormat.ROW_BLOCK_WISE) { int rix = (int) ((pred.rowStart - 1) % brlen); mb = mb.sliceOperations(rix, rix, (int) (pred.colStart - 1), (int) (pred.colEnd - 1), new MatrixBlock()); } if (_partitionFormat == PDataPartitionFormat.COLUMN_BLOCK_WISE) { int cix = (int) ((pred.colStart - 1) % bclen); mb = mb.sliceOperations((int) (pred.rowStart - 1), (int) (pred.rowEnd - 1), cix, cix, new MatrixBlock()); } } //NOTE: currently no special treatment of non-existing partitions necessary // because empty blocks are written anyway } catch (Exception ex) { throw new CacheException(ex); } if (DMLScript.STATISTICS) { long t1 = System.nanoTime(); CacheStatistics.incrementAcquireRTime(t1 - t0); } return mb; }