Search in sources :

Example 21 with WeakReference

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

the class MemoryTest method testAvoidGCWithExtantBuffer.

public void testAvoidGCWithExtantBuffer() throws Exception {
    if (!Platform.HAS_BUFFERS)
        return;
    Memory m = new Memory(1024);
    m.clear();
    ByteBuffer b = m.getByteBuffer(0, m.size());
    Reference<Memory> ref = new WeakReference<Memory>(m);
    Reference<ByteBuffer> bref = new WeakReference<ByteBuffer>(b);
    // Create a second byte buffer "equal" to the first
    m = new Memory(1024);
    m.clear();
    m.getByteBuffer(0, m.size());
    m = null;
    System.gc();
    Memory.purge();
    for (int i = 0; i < GC_WAITS && ref.get() != null; i++) {
        Thread.sleep(GC_WAIT_INTERVAL);
        System.gc();
        Memory.purge();
    }
    assertNotNull("Memory GC'd while NIO Buffer still exists", ref.get());
    // Avoid IBM J9 optimization resulting in premature GC of buffer
    b.put((byte) 0);
    b = null;
    System.gc();
    Memory.purge();
    for (int i = 0; i < GC_WAITS && (bref.get() != null || ref.get() != null); i++) {
        Thread.sleep(GC_WAIT_INTERVAL);
        System.gc();
        Memory.purge();
    }
    assertNull("Buffer not GC'd\n", bref.get());
    assertNull("Memory not GC'd after buffer GC'd\n", ref.get());
}
Also used : WeakReference(java.lang.ref.WeakReference) ByteBuffer(java.nio.ByteBuffer)

Example 22 with WeakReference

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

the class CallbacksTest method testStringCallbackMemoryReclamation.

public void testStringCallbackMemoryReclamation() throws InterruptedException {
    TestLibrary.StringCallback cb = new TestLibrary.StringCallback() {

        @Override
        public String callback(String arg, String arg2) {
            return arg + arg2;
        }
    };
    // A little internal groping
    Map<?, ?> m = CallbackReference.allocations;
    m.clear();
    Charset charset = Charset.forName(Native.getDefaultStringEncoding());
    String arg = getName() + "1" + charset.decode(charset.encode(UNICODE));
    String arg2 = getName() + "2" + charset.decode(charset.encode(UNICODE));
    String value = lib.callStringCallback(cb, arg, arg2);
    WeakReference<Object> ref = new WeakReference<Object>(value);
    arg = null;
    value = null;
    System.gc();
    for (int i = 0; i < 100 && (ref.get() != null || m.size() > 0); ++i) {
        try {
            // Give the GC a chance to run
            Thread.sleep(10);
            System.gc();
        } finally {
        }
    }
    assertNull("NativeString reference not GC'd", ref.get());
    assertEquals("NativeString reference still held: " + m.values(), 0, m.size());
}
Also used : WeakReference(java.lang.ref.WeakReference) Charset(java.nio.charset.Charset)

Example 23 with WeakReference

use of java.lang.ref.WeakReference in project Talon-for-Twitter by klinker24.

the class ImageUtils method imageUrlAsyncTask.

private static void imageUrlAsyncTask(final Context context, final ImageView imageView, final BitmapLruCache mCache, final boolean profile, final String url) {
    final WeakReference<ImageView> mImageViewRef = new WeakReference<ImageView>(imageView);
    Thread imageDownload = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                // Return early if the ImageView has disappeared.
                if (null == mImageViewRef.get()) {
                    return;
                }
                // Now we're not on the main thread we can check all caches
                CacheableBitmapDrawable result;
                result = mCache.get(url, null);
                if (null == result || profile) {
                    String mUrl = url;
                    if (url.contains("twitpic")) {
                        try {
                            URL address = new URL(url);
                            HttpURLConnection connection = (HttpURLConnection) address.openConnection(Proxy.NO_PROXY);
                            connection.setConnectTimeout(1000);
                            connection.setInstanceFollowRedirects(false);
                            connection.setReadTimeout(1000);
                            connection.connect();
                            String expandedURL = connection.getHeaderField("Location");
                            if (expandedURL != null) {
                                mUrl = expandedURL;
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    // The bitmap isn't cached so download from the web
                    HttpURLConnection conn = (HttpURLConnection) new URL(mUrl).openConnection();
                    InputStream is = new BufferedInputStream(conn.getInputStream());
                    Bitmap b = decodeSampledBitmapFromResourceMemOpt(is, 500, 500);
                    try {
                        is.close();
                    } catch (Exception e) {
                    }
                    try {
                        conn.disconnect();
                    } catch (Exception e) {
                    }
                    // Add to cache
                    try {
                        result = mCache.put(mUrl, b);
                    } catch (Exception e) {
                        result = null;
                    }
                }
                final CacheableBitmapDrawable fResult = result;
                ((Activity) context).runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            final ImageView iv = mImageViewRef.get();
                            if (null != iv && iv.getVisibility() != View.GONE) {
                                iv.setImageDrawable(fResult);
                                Animation fadeInAnimation = AnimationUtils.loadAnimation(context, R.anim.fade_in);
                                iv.startAnimation(fadeInAnimation);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            } catch (IOException e) {
                Log.e("ImageUrlAsyncTask", e.toString());
            } catch (OutOfMemoryError e) {
                Log.v("ImageUrlAsyncTask", "Out of memory error here");
            } catch (Exception e) {
                // something else
                e.printStackTrace();
            }
        }
    });
    imageDownload.setPriority(8);
    imageDownload.start();
}
Also used : BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) URL(java.net.URL) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) IOException(java.io.IOException) Bitmap(android.graphics.Bitmap) HttpURLConnection(java.net.HttpURLConnection) BufferedInputStream(java.io.BufferedInputStream) WeakReference(java.lang.ref.WeakReference) Animation(android.view.animation.Animation) CacheableBitmapDrawable(uk.co.senab.bitmapcache.CacheableBitmapDrawable) ImageView(android.widget.ImageView)

Example 24 with WeakReference

use of java.lang.ref.WeakReference in project Klyph by jonathangerbaud.

the class FriendRequestService method onCreate.

@Override
public void onCreate() {
    HandlerThread thread = new HandlerThread("ServiceStartArguments", android.os.Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();
    mServiceLooper = thread.getLooper();
    mServiceHandler = new ServiceHandler(mServiceLooper, new WeakReference<Service>(this));
}
Also used : HandlerThread(android.os.HandlerThread) WeakReference(java.lang.ref.WeakReference)

Example 25 with WeakReference

use of java.lang.ref.WeakReference in project Klyph by jonathangerbaud.

the class NotificationService method onCreate.

@Override
public void onCreate() {
    // Why initialize device values ?
    // Because we need the density to calculate image size
    // In notification request
    KlyphDevice.initDeviceValues(this);
    HandlerThread thread = new HandlerThread("ServiceStartArguments", android.os.Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();
    mServiceLooper = thread.getLooper();
    mServiceHandler = new ServiceHandler(mServiceLooper, new WeakReference<Service>(this));
}
Also used : HandlerThread(android.os.HandlerThread) WeakReference(java.lang.ref.WeakReference)

Aggregations

WeakReference (java.lang.ref.WeakReference)277 ArrayList (java.util.ArrayList)31 HashMap (java.util.HashMap)19 Map (java.util.Map)19 Field (java.lang.reflect.Field)18 Activity (android.app.Activity)17 Method (java.lang.reflect.Method)15 File (java.io.File)14 IOException (java.io.IOException)13 URLClassLoader (java.net.URLClassLoader)13 Test (org.junit.Test)13 Reference (java.lang.ref.Reference)12 ReferenceQueue (java.lang.ref.ReferenceQueue)12 Iterator (java.util.Iterator)12 Resources (android.content.res.Resources)10 Handler (android.os.Handler)10 AbstractModule (com.google.inject.AbstractModule)10 Injector (com.google.inject.Injector)10 ArrayMap (android.util.ArrayMap)9 URL (java.net.URL)8