Search in sources :

Example 16 with Reference

use of java.lang.ref.Reference in project jdk8u_jdk by JetBrains.

the class Font2D method getStrike.

FontStrike getStrike(FontStrikeDesc desc, boolean copy) {
    /* Before looking in the map, see if the descriptor matches the
         * last strike returned from this Font2D. This should often be a win
         * since its common for the same font, in the same size to be
         * used frequently, for example in many parts of a UI.
         *
         * If its not the same then we use the descriptor to locate a
         * Reference to the strike. If it exists and points to a strike,
         * then we update the last strike to refer to that and return it.
         *
         * If the key isn't in the map, or its reference object has been
         * collected, then we create a new strike, put it in the map and
         * set it to be the last strike.
         */
    FontStrike strike = (FontStrike) lastFontStrike.get();
    if (strike != null && desc.equals(strike.desc)) {
        //strike.lastlookupTime = System.currentTimeMillis();
        return strike;
    } else {
        Reference strikeRef = strikeCache.get(desc);
        if (strikeRef != null) {
            strike = (FontStrike) strikeRef.get();
            if (strike != null) {
                //strike.lastlookupTime = System.currentTimeMillis();
                lastFontStrike = new SoftReference(strike);
                StrikeCache.refStrike(strike);
                return strike;
            }
        }
        /* When we create a new FontStrike instance, we *must*
             * ask the StrikeCache for a reference. We must then ensure
             * this reference remains reachable, by storing it in the
             * Font2D's strikeCache map.
             * So long as the Reference is there (reachable) then if the
             * reference is cleared, it will be enqueued for disposal.
             * If for some reason we explicitly remove this reference, it
             * must only be done when holding a strong reference to the
             * referent (the FontStrike), or if the reference is cleared,
             * then we must explicitly "dispose" of the native resources.
             * The only place this currently happens is in this same method,
             * where we find a cleared reference and need to overwrite it
             * here with a new reference.
             * Clearing the whilst holding a strong reference, should only
             * be done if the
             */
        if (copy) {
            desc = new FontStrikeDesc(desc);
        }
        strike = createStrike(desc);
        //StrikeCache.addStrike();
        /* If we are creating many strikes on this font which
             * involve non-quadrant rotations, or more general
             * transforms which include shears, then force the use
             * of weak references rather than soft references.
             * This means that it won't live much beyond the next GC,
             * which is what we want for what is likely a transient strike.
             */
        int txType = desc.glyphTx.getType();
        if (txType == AffineTransform.TYPE_GENERAL_TRANSFORM || (txType & AffineTransform.TYPE_GENERAL_ROTATION) != 0 && strikeCache.size() > 10) {
            strikeRef = StrikeCache.getStrikeRef(strike, true);
        } else {
            strikeRef = StrikeCache.getStrikeRef(strike);
        }
        strikeCache.put(desc, strikeRef);
        //strike.lastlookupTime = System.currentTimeMillis();
        lastFontStrike = new SoftReference(strike);
        StrikeCache.refStrike(strike);
        return strike;
    }
}
Also used : SoftReference(java.lang.ref.SoftReference) Reference(java.lang.ref.Reference) SoftReference(java.lang.ref.SoftReference)

Example 17 with Reference

use of java.lang.ref.Reference in project jdk8u_jdk by JetBrains.

the class FileFont method deregisterFontAndClearStrikeCache.

// MACOSX - end
/* This is called when a font scaler is determined to
     * be unusable (ie bad).
     * We want to replace current scaler with NullFontScaler, so
     * we never try to use same font scaler again.
     * Scaler native resources could have already been disposed
     * or they will be eventually by Java2D disposer.
     * However, it should be safe to call dispose() explicitly here.
     *
     * For safety we also invalidate all strike's scaler context.
     * So, in case they cache pointer to native scaler
     * it will not ever be used.
     *
     * It also appears desirable to remove all the entries from the
     * cache so no other code will pick them up. But we can't just
     * 'delete' them as code may be using them. And simply dropping
     * the reference to the cache will make the reference objects
     * unreachable and so they will not get disposed.
     * Since a strike may hold (via java arrays) native pointers to many
     * rasterised glyphs, this would be a memory leak.
     * The solution is :
     * - to move all the entries to another map where they
     *   are no longer locatable
     * - update FontStrikeDisposer to be able to distinguish which
     * map they are held in via a boolean flag
     * Since this isn't expected to be anything other than an extremely
     * rare maybe it is not worth doing this last part.
     */
synchronized void deregisterFontAndClearStrikeCache() {
    SunFontManager fm = SunFontManager.getInstance();
    fm.deRegisterBadFont(this);
    for (Reference strikeRef : strikeCache.values()) {
        if (strikeRef != null) {
            /* NB we know these are all FileFontStrike instances
                 * because the cache is on this FileFont
                 */
            FileFontStrike strike = (FileFontStrike) strikeRef.get();
            if (strike != null && strike.pScalerContext != 0L) {
                scaler.invalidateScalerContext(strike.pScalerContext);
            }
        }
    }
    if (scaler != null) {
        scaler.dispose();
    }
    scaler = FontScaler.getNullScaler();
}
Also used : Reference(java.lang.ref.Reference)

Example 18 with Reference

use of java.lang.ref.Reference in project jna by java-native-access.

the class MemoryTest method testRemoveAllocatedMemoryMap.

public void testRemoveAllocatedMemoryMap() throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
    // Make sure there are no remaining allocations
    Memory.disposeAll();
    // get a reference to the allocated memory
    Field allocatedMemoryField = Memory.class.getDeclaredField("allocatedMemory");
    allocatedMemoryField.setAccessible(true);
    Map<Memory, Reference<Memory>> allocatedMemory = (Map<Memory, Reference<Memory>>) allocatedMemoryField.get(null);
    assertEquals(0, allocatedMemory.size());
    // Test allocation and ensure it is accounted for
    Memory mem = new Memory(1024);
    assertEquals(1, allocatedMemory.size());
    // Dispose memory and ensure allocation is removed from allocatedMemory-Map
    mem.dispose();
    assertEquals(0, allocatedMemory.size());
}
Also used : Field(java.lang.reflect.Field) Reference(java.lang.ref.Reference) WeakReference(java.lang.ref.WeakReference) Map(java.util.Map)

Example 19 with Reference

use of java.lang.ref.Reference in project powermock by powermock.

the class AbstractClassGenerator method create.

protected Object create(Object key) {
    try {
        Class gen = null;
        synchronized (source) {
            ClassLoader loader = getClassLoader();
            Map cache2 = null;
            cache2 = (Map) source.cache.get(loader);
            if (cache2 == null) {
                cache2 = new HashMap();
                cache2.put(NAME_KEY, new HashSet());
                source.cache.put(loader, cache2);
            } else if (useCache) {
                Reference ref = (Reference) cache2.get(key);
                gen = (Class) ((ref == null) ? null : ref.get());
            }
            if (gen == null) {
                Object save = CURRENT.get();
                CURRENT.set(this);
                try {
                    this.key = key;
                    if (attemptLoad) {
                        try {
                            gen = loader.loadClass(getClassName());
                        } catch (ClassNotFoundException e) {
                        // ignore
                        }
                    }
                    if (gen == null) {
                        byte[] b = strategy.generate(this);
                        String className = ClassNameReader.getClassName(new ClassReader(b));
                        getClassNameCache(loader).add(className);
                        gen = ReflectUtils.defineClass(className, b, loader);
                    }
                    if (useCache) {
                        cache2.put(key, new WeakReference(gen));
                    }
                    return firstInstance(gen);
                } finally {
                    CURRENT.set(save);
                }
            }
        }
        return firstInstance(gen);
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new CodeGenerationException(e);
    }
}
Also used : HashMap(java.util.HashMap) WeakHashMap(java.util.WeakHashMap) Reference(java.lang.ref.Reference) WeakReference(java.lang.ref.WeakReference) WeakReference(java.lang.ref.WeakReference) ClassReader(org.powermock.api.mockito.repackaged.asm.ClassReader) Map(java.util.Map) HashMap(java.util.HashMap) WeakHashMap(java.util.WeakHashMap) HashSet(java.util.HashSet)

Example 20 with Reference

use of java.lang.ref.Reference in project robovm by robovm.

the class ReferenceQueueTest method test_removeJ.

/**
     * java.lang.ref.ReferenceQueue#remove(long)
     */
public void test_removeJ() {
    try {
        assertNull("Queue should be empty. (poll)", rq.poll());
        assertNull("Queue should be empty. (remove(1))", rq.remove((long) 1));
        Thread ct = new Thread(new ChildThread());
        ct.start();
        Reference ret = rq.remove(0L);
        assertNotNull("Delayed remove failed.", ret);
    } catch (InterruptedException e) {
        fail("InterruptedExeException during test : " + e.getMessage());
    } catch (Exception e) {
        fail("Exception during test : " + e.getMessage());
    }
    Object obj = new Object();
    WeakReference wr = new WeakReference(obj, rq);
    Boolean b = new Boolean(true);
    SoftReference sr = new SoftReference(b, rq);
    String str = "Test";
    PhantomReference pr = new PhantomReference(str, rq);
    pr.enqueue();
    wr.enqueue();
    sr.enqueue();
    try {
        Reference result = rq.remove(1L);
        assertTrue((Boolean) result.get());
        result = rq.remove(1L);
        assertEquals(obj, result.get());
        result = rq.remove(1L);
        assertNull(result.get());
    } catch (IllegalArgumentException e1) {
        fail("IllegalArgumentException was thrown.");
    } catch (InterruptedException e1) {
        fail("InterruptedException was thrown.");
    }
    rq = new ReferenceQueue();
    isThrown = false;
    assertNull(rq.poll());
    class RemoveThread extends Thread {

        public void run() {
            try {
                rq.remove(1000L);
            } catch (InterruptedException ie) {
                isThrown = true;
            }
        }
    }
    RemoveThread rt = new RemoveThread();
    rt.start();
    try {
        Thread.sleep(10);
    } catch (InterruptedException ie) {
    }
    rt.interrupt();
    try {
        Thread.sleep(10);
    } catch (InterruptedException ie) {
    }
    assertTrue(isThrown);
    assertNull(rq.poll());
    try {
        rq.remove(-1);
        fail("IllegalArgumentException expected.");
    } catch (IllegalArgumentException iae) {
    //expected
    } catch (InterruptedException e) {
        fail("Unexpected InterruptedException.");
    }
}
Also used : ReferenceQueue(java.lang.ref.ReferenceQueue) PhantomReference(java.lang.ref.PhantomReference) Reference(java.lang.ref.Reference) SoftReference(java.lang.ref.SoftReference) WeakReference(java.lang.ref.WeakReference) SoftReference(java.lang.ref.SoftReference) WeakReference(java.lang.ref.WeakReference) PhantomReference(java.lang.ref.PhantomReference)

Aggregations

Reference (java.lang.ref.Reference)31 WeakReference (java.lang.ref.WeakReference)17 PhantomReference (java.lang.ref.PhantomReference)10 ReferenceQueue (java.lang.ref.ReferenceQueue)10 SoftReference (java.lang.ref.SoftReference)10 Field (java.lang.reflect.Field)5 Map (java.util.Map)5 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 ConcurrentMap (java.util.concurrent.ConcurrentMap)3 IOException (java.io.IOException)2 AccessControlContext (java.security.AccessControlContext)2 HashSet (java.util.HashSet)2 Iterator (java.util.Iterator)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 AtomicReference (java.util.concurrent.atomic.AtomicReference)2 Supplier (com.google.common.base.Supplier)1 SoftReference (com.intellij.reference.SoftReference)1 SideEffect (dalvik.annotation.SideEffect)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1