java.lang.ref.SoftReference Java Examples
The following examples show how to use
java.lang.ref.SoftReference.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: EmojiUtil.java From XMPPSample_Studio with Apache License 2.0 | 6 votes |
private EmojiUtil(Context context) { this.context = context; density = context.getResources().getDisplayMetrics().density; try { if (density >= 1.5f) { this.isHdpi = true; InputStream localInputStream = context.getAssets().open("emoji/emoji_2x.png"); Options opts = new Options(); opts.inPurgeable = true; opts.inInputShareable = true; emojiImages = BitmapFactory.decodeStream(localInputStream, null, opts); } String[] index = EMOJI_INDEX.split("\n"); emojiRects = new HashMap<String, Rect>(); emojiDrawables = new HashMap<String, SoftReference<Drawable>>(); for (int i = 0; i < index.length; i++) { String[] emojis = index[i].split("-"); for (int j = 0; j < emojis.length; j++) { emojiRects.put(emojis[j], new Rect(j * 40, i * 40, 40 * (j + 1), 40 * (i + 1))); } } } catch (IOException localIOException) { } }
Example #2
Source File: StrikeCache.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
public static Reference<FontStrike> getStrikeRef(FontStrike strike, boolean weak) { /* Some strikes may have no disposer as there's nothing * for them to free, as they allocated no native resource * eg, if they did not allocate resources because of a problem, * or they never hold native resources. So they create no disposer. * But any strike that reaches here that has a null disposer is * a potential memory leak. */ if (strike.disposer == null) { if (weak) { return new WeakReference<>(strike); } else { return new SoftReference<>(strike); } } if (weak) { return new WeakDisposerRef(strike); } else { return new SoftDisposerRef(strike); } }
Example #3
Source File: AbstractNbTaskWrapper.java From netbeans with Apache License 2.0 | 6 votes |
@Override public void taskDataUpdated (TaskDataListener.TaskDataEvent event) { if (event.getTask() == task) { if (event.getTaskData() != null && !event.getTaskData().isPartial()) { repositoryDataRef = new SoftReference<TaskData>(event.getTaskData()); } if (event.getTaskDataUpdated()) { NbTaskDataModel m = model; if (m != null) { try { m.refresh(); } catch (CoreException ex) { LOG.log(Level.INFO, null, ex); } } AbstractNbTaskWrapper.this.taskDataUpdated(); } } }
Example #4
Source File: Snapshot.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 6 votes |
public synchronized Enumeration getFinalizerObjects() { Vector obj; if (finalizablesCache != null && (obj = finalizablesCache.get()) != null) { return obj.elements(); } JavaClass clazz = findClass("java.lang.ref.Finalizer"); JavaObject queue = (JavaObject) clazz.getStaticField("queue"); JavaThing tmp = queue.getField("head"); Vector<JavaHeapObject> finalizables = new Vector<JavaHeapObject>(); if (tmp != getNullThing()) { JavaObject head = (JavaObject) tmp; while (true) { JavaHeapObject referent = (JavaHeapObject) head.getField("referent"); JavaThing next = head.getField("next"); if (next == getNullThing() || next.equals(head)) { break; } head = (JavaObject) next; finalizables.add(referent); } } finalizablesCache = new SoftReference<Vector>(finalizables); return finalizables.elements(); }
Example #5
Source File: LogManagerImpl.java From baratine with GNU General Public License v2.0 | 6 votes |
/** * Returns the named logger. */ @Override public synchronized Logger getLogger(String name) { SoftReference<EnvironmentLogger> envLoggerRef = _envLoggers.get(name); EnvironmentLogger envLogger = null; if (envLoggerRef != null) envLogger = envLoggerRef.get(); if (envLogger == null) envLogger = addLogger(name, null); Logger customLogger = envLogger.getLogger(); if (customLogger != null) return customLogger; else return envLogger; }
Example #6
Source File: ManagedChannelOrphanWrapper.java From grpc-nebula-java with Apache License 2.0 | 6 votes |
ManagedChannelReference( ManagedChannelOrphanWrapper orphanable, ManagedChannel channel, ReferenceQueue<ManagedChannelOrphanWrapper> refqueue, ConcurrentMap<ManagedChannelReference, ManagedChannelReference> refs) { super(orphanable, refqueue); allocationSite = new SoftReference<RuntimeException>( ENABLE_ALLOCATION_TRACKING ? new RuntimeException("ManagedChannel allocation site") : missingCallSite); this.channel = channel; this.refqueue = refqueue; this.refs = refs; this.refs.put(this, this); cleanQueue(refqueue); }
Example #7
Source File: ImageCache.java From dragonwell8_jdk with GNU General Public License v2.0 | 6 votes |
private Entry getEntry(Object key, GraphicsConfiguration config, int w, int h, Object[] args) { Entry entry; Iterator<SoftReference<Entry>> iter = entries.listIterator(); while (iter.hasNext()) { SoftReference<Entry> ref = iter.next(); entry = ref.get(); if (entry == null) { // SoftReference was invalidated, remove the entry iter.remove(); } else if (entry.equals(config, w, h, args)) { // Put most recently used entries at the head iter.remove(); entries.addFirst(ref); return entry; } } // Entry doesn't exist entry = new Entry(config, w, h, args); if (entries.size() >= maxCount) { entries.removeLast(); } entries.addFirst(new SoftReference<Entry>(entry)); return entry; }
Example #8
Source File: FolderOrder.java From netbeans with Apache License 2.0 | 6 votes |
/** Creates order for given folder object. * @param f the folder * @return the order */ public static FolderOrder findFor (FileObject folder) { FolderOrder order = null; synchronized (map) { Reference<FolderOrder> ref = map.get (folder); order = ref == null ? null : ref.get (); if (order == null) { order = new FolderOrder (folder); order.previous = knownOrders.get(folder); order.doRead(order.previous); map.put (folder, new SoftReference<FolderOrder> (order)); } } // always reread the order from disk, so it is uptodate synchronized (order) { order.read (); return order; } }
Example #9
Source File: ResolvedFeaturesTest.java From xtext-extras with Eclipse Public License 2.0 | 6 votes |
@Test public void testSoftReferenceConstructors() { final ResolvedFeatures resolvedOperations = this.toResolvedOperations(SoftReference.class); Assert.assertEquals(1, resolvedOperations.getDeclaredOperations().size()); Assert.assertEquals(2, resolvedOperations.getDeclaredConstructors().size()); final Consumer<IResolvedConstructor> _function = (IResolvedConstructor it) -> { int _size = it.getDeclaration().getParameters().size(); switch (_size) { case 1: Assert.assertEquals("SoftReference(T)", it.getResolvedSignature()); Assert.assertEquals("SoftReference(java.lang.Object)", it.getResolvedErasureSignature()); break; case 2: Assert.assertEquals("SoftReference(T,java.lang.ref.ReferenceQueue<? super T>)", it.getResolvedSignature()); Assert.assertEquals("SoftReference(java.lang.Object,java.lang.ref.ReferenceQueue)", it.getResolvedErasureSignature()); break; default: Assert.fail(("Unexpected constructor: " + it)); break; } }; resolvedOperations.getDeclaredConstructors().forEach(_function); }
Example #10
Source File: ImageCache.java From openjdk-8 with GNU General Public License v2.0 | 6 votes |
private Entry getEntry(Object key, GraphicsConfiguration config, int w, int h, Object[] args) { Entry entry; Iterator<SoftReference<Entry>> iter = entries.listIterator(); while (iter.hasNext()) { SoftReference<Entry> ref = iter.next(); entry = ref.get(); if (entry == null) { // SoftReference was invalidated, remove the entry iter.remove(); } else if (entry.equals(config, w, h, args)) { // Put most recently used entries at the head iter.remove(); entries.addFirst(ref); return entry; } } // Entry doesn't exist entry = new Entry(config, w, h, args); if (entries.size() >= maxCount) { entries.removeLast(); } entries.addFirst(new SoftReference<Entry>(entry)); return entry; }
Example #11
Source File: BufferManager.java From bt with Apache License 2.0 | 6 votes |
@Override @SuppressWarnings("unchecked") public BorrowedBuffer<ByteBuffer> borrowByteBuffer() { Deque<SoftReference<?>> deque = getReleasedBuffersDeque(ByteBuffer.class); SoftReference<ByteBuffer> ref; ByteBuffer buffer = null; do { ref = (SoftReference<ByteBuffer>) deque.pollLast(); if (ref != null) { buffer = ref.get(); } // check if the referenced buffer has been garbage collected } while (ref != null && buffer == null); if (buffer == null) { buffer = ByteBuffer.allocateDirect(bufferSize); } else { // reset buffer before re-using buffer.clear(); } return new DefaultBorrowedBuffer<>(buffer); }
Example #12
Source File: StrikeCache.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
public static Reference getStrikeRef(FontStrike strike, boolean weak) { /* Some strikes may have no disposer as there's nothing * for them to free, as they allocated no native resource * eg, if they did not allocate resources because of a problem, * or they never hold native resources. So they create no disposer. * But any strike that reaches here that has a null disposer is * a potential memory leak. */ if (strike.disposer == null) { if (weak) { return new WeakReference(strike); } else { return new SoftReference(strike); } } if (weak) { return new WeakDisposerRef(strike); } else { return new SoftDisposerRef(strike); } }
Example #13
Source File: ReentrantContextProvider.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
@SuppressWarnings("unchecked") protected final Reference<K> getOrCreateReference(final K ctx) { if (ctx.reference == null) { // Create the reference: switch (refType) { case REF_HARD: ctx.reference = new HardReference<K>(ctx); break; case REF_SOFT: ctx.reference = new SoftReference<K>(ctx); break; default: case REF_WEAK: ctx.reference = new WeakReference<K>(ctx); break; } } return (Reference<K>) ctx.reference; }
Example #14
Source File: ImageCache.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 6 votes |
private Entry getEntry(Object key, GraphicsConfiguration config, int w, int h, Object[] args) { Entry entry; Iterator<SoftReference<Entry>> iter = entries.listIterator(); while (iter.hasNext()) { SoftReference<Entry> ref = iter.next(); entry = ref.get(); if (entry == null) { // SoftReference was invalidated, remove the entry iter.remove(); } else if (entry.equals(config, w, h, args)) { // Put most recently used entries at the head iter.remove(); entries.addFirst(ref); return entry; } } // Entry doesn't exist entry = new Entry(config, w, h, args); if (entries.size() >= maxCount) { entries.removeLast(); } entries.addFirst(new SoftReference<Entry>(entry)); return entry; }
Example #15
Source File: MethodRef.java From jdk8u_jdk with GNU General Public License v2.0 | 6 votes |
Method get() { if (this.methodRef == null) { return null; } Method method = this.methodRef.get(); if (method == null) { method = find(this.typeRef.get(), this.signature); if (method == null) { this.signature = null; this.methodRef = null; this.typeRef = null; return null; } this.methodRef = new SoftReference<>(method); } return isPackageAccessible(method.getDeclaringClass()) ? method : null; }
Example #16
Source File: ClassLookupCache.java From emissary with Apache License 2.0 | 6 votes |
/** * Look up a class in the cache. * * @param className The class name to find. * @return If the class name is currently known to the cache, the corresponding {@link Class} object is returned. * Otherwise {@code null}. */ public static Class<?> get(final String className) { // Currently there is at most one cached lookup per thread, so // we can just check if the current thread knows about the // given class name. final SoftReference<NamedClass<?>> softResult = cachedLookupResult.get(); if (softResult == null) { return null; // Nothing is currently cached in this thread. } final NamedClass<?> actualResult = softResult.get(); if (actualResult == null) { return null; // There was something cached but it's been lost. } // We do have a cached lookup. It can be used iff it matches // the given name. return actualResult.getClass(className); }
Example #17
Source File: FragmentFactory.java From MVP-Dagger2-Rxjava-Retrofit with Apache License 2.0 | 6 votes |
public static BaseFragment getFragment(int pos) { BaseFragment fragment = null; if (null != arr.get(pos)) fragment = arr.get(pos).get(); if (null == fragment) { switch (pos) { case 0: fragment = new MainPageFragment(); break; case 1: fragment = new WantingFragment(); break; case 2: fragment = new MessageFragment(); break; case 3: fragment = new MineFragment(); break; } arr.put(0, new SoftReference<BaseFragment>(fragment)); } return fragment; }
Example #18
Source File: ZoneInfoOld.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
/** * Returns a Map from alias time zone IDs to their standard * time zone IDs. * * @return the Map that holds the mappings from alias time zone IDs * to their standard time zone IDs, or null if * <code>ZoneInfoOldMappings</code> file is not available. */ public synchronized static Map<String, String> getAliasTable() { Map<String, String> aliases = getCachedAliasTable(); if (aliases == null) { aliases = ZoneInfoFile.getZoneAliases(); if (aliases != null) { if (!USE_OLDMAPPING) { // Remove the conflicting IDs from the alias table. for (String key : conflictingIDs) { aliases.remove(key); } } aliasTable = new SoftReference<Map<String, String>>(aliases); } } return aliases; }
Example #19
Source File: TCPTransport.java From openjdk-8 with GNU General Public License v2.0 | 6 votes |
/** * Verify that the given AccessControlContext has permission to * accept this connection. */ void checkAcceptPermission(SecurityManager sm, AccessControlContext acc) { /* * Note: no need to synchronize on cache-related fields, since this * method only gets called from the ConnectionHandler's thread. */ if (sm != cacheSecurityManager) { okContext = null; authCache = new WeakHashMap<AccessControlContext, Reference<AccessControlContext>>(); cacheSecurityManager = sm; } if (acc.equals(okContext) || authCache.containsKey(acc)) { return; } InetAddress addr = socket.getInetAddress(); String host = (addr != null) ? addr.getHostAddress() : "*"; sm.checkAccept(host, socket.getPort()); authCache.put(acc, new SoftReference<AccessControlContext>(acc)); okContext = acc; }
Example #20
Source File: MethodTypeForm.java From jdk8u60 with GNU General Public License v2.0 | 5 votes |
synchronized public LambdaForm setCachedLambdaForm(int which, LambdaForm form) { // Simulate a CAS, to avoid racy duplication of results. SoftReference<LambdaForm> entry = lambdaForms[which]; if (entry != null) { LambdaForm prev = entry.get(); if (prev != null) { return prev; } } lambdaForms[which] = new SoftReference<>(form); return form; }
Example #21
Source File: AquaUtils.java From hottub with GNU General Public License v2.0 | 5 votes |
T get() { T referent; if (objectRef != null && (referent = objectRef.get()) != null) return referent; referent = create(); objectRef = new SoftReference<T>(referent); return referent; }
Example #22
Source File: ZoneNode.java From jdk8u60 with GNU General Public License v2.0 | 5 votes |
NameNode populate(DnsName zone, ResourceRecords rrs) { // assert zone.get(0).equals(""); // zone has root label // assert (zone.size() == (depth() + 1)); // +1 due to root label NameNode newContents = new NameNode(null); for (int i = 0; i < rrs.answer.size(); i++) { ResourceRecord rr = rrs.answer.elementAt(i); DnsName n = rr.getName(); // Ignore resource records whose names aren't within the zone's // domain. Also skip records of the zone's top node, since // the zone's root NameNode is already in place. if ((n.size() > zone.size()) && n.startsWith(zone)) { NameNode nnode = newContents.add(n, zone.size()); if (rr.getType() == ResourceRecord.TYPE_NS) { nnode.setZoneCut(true); } } } // The zone's SOA record is the first record in the answer section. ResourceRecord soa = rrs.answer.firstElement(); synchronized (this) { contentsRef = new SoftReference<NameNode>(newContents); serialNumber = getSerialNumber(soa); setExpiration(getMinimumTtl(soa)); return newContents; } }
Example #23
Source File: ReferenceTypeImpl.java From openjdk-8-source with GNU General Public License v2.0 | 5 votes |
private void getConstantPoolInfo() { JDWP.ReferenceType.ConstantPool jdwpCPool; if (!vm.canGetConstantPool()) { throw new UnsupportedOperationException(); } if (constantPoolInfoGotten) { return; } else { try { jdwpCPool = JDWP.ReferenceType.ConstantPool.process(vm, this); } catch (JDWPException exc) { if (exc.errorCode() == JDWP.Error.ABSENT_INFORMATION) { constanPoolCount = 0; constantPoolBytesRef = null; constantPoolInfoGotten = true; return; } else { throw exc.toJDIException(); } } byte[] cpbytes; constanPoolCount = jdwpCPool.count; cpbytes = jdwpCPool.bytes; constantPoolBytesRef = new SoftReference<byte[]>(cpbytes); constantPoolInfoGotten = true; } }
Example #24
Source File: SoftReferenceDemo.java From code with Apache License 2.0 | 5 votes |
public static void softRef_Memory_NotEnough() { Object o = new Object(); SoftReference<Object> softReference = new SoftReference<>(o); System.out.println("---内存充足---"); System.out.println("原引用:"+o); System.out.println("软引用:"+softReference.get()); o = null; try { // -Xms9m -Xmx9m 新生代:老年代=1:2 3MB:6MB // 大对象直接如老年代 //byte[] bytes = new byte[6*1024*1024];//6MB 内存足够,不会回收软引用 byte[] bytes = new byte[7 * 1024 * 1024];//7MB OOM触发GC,回收软引用 } catch (Throwable e) { System.out.println("---原引用置为null, OOM触发GC---"); e.printStackTrace(); // java.lang.OutOfMemoryError: Java heap space // at cn.lastwhisper.jvm.gc.reference.SoftReferenceDemo.softRef_Memory_NotEnough(SoftReferenceDemo.java:46) // at cn.lastwhisper.jvm.gc.reference.SoftReferenceDemo.main(SoftReferenceDemo.java:15) } finally { System.out.println("原引用:"+o);//null System.out.println("软引用:"+softReference.get());// null 内存不足被回收 // 是否会被 GC ?不会因为 softReference GCRoots 可到达 System.out.println("softReference:"+softReference); } }
Example #25
Source File: ZoneNode.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
NameNode populate(DnsName zone, ResourceRecords rrs) { // assert zone.get(0).equals(""); // zone has root label // assert (zone.size() == (depth() + 1)); // +1 due to root label NameNode newContents = new NameNode(null); for (int i = 0; i < rrs.answer.size(); i++) { ResourceRecord rr = rrs.answer.elementAt(i); DnsName n = rr.getName(); // Ignore resource records whose names aren't within the zone's // domain. Also skip records of the zone's top node, since // the zone's root NameNode is already in place. if ((n.size() > zone.size()) && n.startsWith(zone)) { NameNode nnode = newContents.add(n, zone.size()); if (rr.getType() == ResourceRecord.TYPE_NS) { nnode.setZoneCut(true); } } } // The zone's SOA record is the first record in the answer section. ResourceRecord soa = rrs.answer.firstElement(); synchronized (this) { contentsRef = new SoftReference<NameNode>(newContents); serialNumber = getSerialNumber(soa); setExpiration(getMinimumTtl(soa)); return newContents; } }
Example #26
Source File: Introspector.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
/** * Returns the list of methods cached for the given class, or {@code null} * if not cached. */ private static List<Method> getCachedMethods(Class<?> clazz) { // return cached methods if possible SoftReference<List<Method>> ref = cache.get(clazz); if (ref != null) { List<Method> cached = ref.get(); if (cached != null) return cached; } return null; }
Example #27
Source File: DateTimeFormatterBuilder.java From JDKSourceCode1.8 with MIT License | 5 votes |
private String getDisplayName(String id, int type, Locale locale) { if (textStyle == TextStyle.NARROW) { return null; } String[] names; SoftReference<Map<Locale, String[]>> ref = cache.get(id); Map<Locale, String[]> perLocale = null; if (ref == null || (perLocale = ref.get()) == null || (names = perLocale.get(locale)) == null) { names = TimeZoneNameUtility.retrieveDisplayNames(id, locale); if (names == null) { return null; } names = Arrays.copyOfRange(names, 0, 7); names[5] = TimeZoneNameUtility.retrieveGenericDisplayName(id, TimeZone.LONG, locale); if (names[5] == null) { names[5] = names[0]; // use the id } names[6] = TimeZoneNameUtility.retrieveGenericDisplayName(id, TimeZone.SHORT, locale); if (names[6] == null) { names[6] = names[0]; } if (perLocale == null) { perLocale = new ConcurrentHashMap<>(); } perLocale.put(locale, names); cache.put(id, new SoftReference<>(perLocale)); } switch (type) { case STD: return names[textStyle.zoneNameStyleIndex() + 1]; case DST: return names[textStyle.zoneNameStyleIndex() + 3]; } return names[textStyle.zoneNameStyleIndex() + 5]; }
Example #28
Source File: MethodRef.java From jdk8u-jdk with GNU General Public License v2.0 | 5 votes |
void set(Method method) { if (method == null) { this.signature = null; this.methodRef = null; this.typeRef = null; } else { this.signature = method.toGenericString(); this.methodRef = new SoftReference<>(method); this.typeRef = new WeakReference<Class<?>>(method.getDeclaringClass()); } }
Example #29
Source File: TimeZoneNameUtility.java From jdk8u-jdk with GNU General Public License v2.0 | 5 votes |
private static String[] retrieveDisplayNamesImpl(String id, Locale locale) { LocaleServiceProviderPool pool = LocaleServiceProviderPool.getPool(TimeZoneNameProvider.class); String[] names; Map<Locale, String[]> perLocale = null; SoftReference<Map<Locale, String[]>> ref = cachedDisplayNames.get(id); if (Objects.nonNull(ref)) { perLocale = ref.get(); if (Objects.nonNull(perLocale)) { names = perLocale.get(locale); if (Objects.nonNull(names)) { return names; } } } // build names array names = new String[7]; names[0] = id; for (int i = 1; i <= 6; i ++) { names[i] = pool.getLocalizedObject(TimeZoneNameGetter.INSTANCE, locale, i<5 ? (i<3 ? "std" : "dst") : "generic", i%2, id); } if (Objects.isNull(perLocale)) { perLocale = new ConcurrentHashMap<>(); } perLocale.put(locale, names); ref = new SoftReference<>(perLocale); cachedDisplayNames.put(id, ref); return names; }
Example #30
Source File: Effect.java From jdk8u_jdk with GNU General Public License v2.0 | 5 votes |
protected byte[] getTmpByteArray3(int size) { byte[] tmp; if (tmpByteArray3 == null || (tmp = tmpByteArray3.get()) == null || tmp.length < size) { // create new array tmp = new byte[size]; tmpByteArray3 = new SoftReference<byte[]>(tmp); } return tmp; }