Skip to content

Commit

Permalink
Added implementation of WeakHandler
Browse files Browse the repository at this point in the history
  • Loading branch information
Dmytro Voronkevych committed Aug 27, 2014
1 parent 5ce5ef9 commit cdd3c94
Show file tree
Hide file tree
Showing 7 changed files with 886 additions and 1 deletion.
68 changes: 67 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,70 @@
android-weak-handler
Android Weak Handler
====================

Memory safer implementation of android.os.Handler

Problem
-------

Original implementation of Handler always keeps hard reference to handler in queue of execution.
Any object in Message or Runnable posted to `android.os.Handler` will be hard referenced for some time.
If you create anonymous Runnable and call to `postDelayed` with large timeout, that Runnable will be held
in memory until timeout passes. Even if your Runnable seems small, it indirectly references owner class,
which is usually something as big as Activity or Fragment.

Very soon we will post article with much more details.

Solution
--------

`WeakHandler` is trickier then `android.os.Handler` , it will keep `WeakReferences` to runnables and messages,
and GC could collect them once `WeakHandler` instance is not referenced any more.

![Screenshot](WeakHandler.png)

Usage
-----
Clone project to your local machine, then run
```shell
cd android-weak-handler
gradle uploadArchives
```

Add reference to your build.gradle:
```groovy
repositories {
mavenLocal()
}
dependencies {
compile 'com.badoo.mobile:android-weak-handler:1.0'
}
```

Use WeakHandler as you normally would use Handler

```java
import com.badoo.mobile.util.WeakHandler;

public class ExampleActivity extends Activity {

private WeakHandler mHandler; // We still need at least one hard reference to WeakHandler

protected void onCreate(Bundle savedInstanceState) {
mHandler = new WeakHandler();
...
}

private void onClick(View view) {
mHandler.postDelayed(new Runnable() {
view.setVisibility(View.INVISIBLE);
}, 5000);
}
}
```

Credits
-------
Weak Handler is brought to you by [Badoo Trading Limited](http:https://corp.badoo.com) and it is released under the [MIT License](http:https://opensource.org/licenses/MIT).

Created by [Dmytro Voronkevych](https://github.com/dmitry-voronkevich)
Binary file added WeakHandler.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
58 changes: 58 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/*
* Copyright (c) 2014 Badoo Trading Limited
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
project.ext.set('VERSION_CODE', 1)
project.ext.set('VERSION_NAME', '1.0')

buildscript {
repositories {
mavenCentral()
}

dependencies {
classpath 'com.android.tools.build:gradle:0.12.+'
}
}

apply plugin: 'com.android.library'

dependencies {
compile "com.android.support:support-annotations:19.1.0"
}


android {
compileSdkVersion 19
buildToolsVersion "19.1.0"

defaultConfig {
versionCode project.VERSION_CODE
versionName project.VERSION_NAME
minSdkVersion 8
targetSdkVersion 19
}
}

if (project.hasProperty('badooMavenScript')) {
apply from: project.badooMavenScript
} else {
apply from: 'mvn-local-support.gradle'
}

59 changes: 59 additions & 0 deletions mvn-local-support.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/*
* Copyright (c) 2014 Badoo Trading Limited
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
apply plugin: 'maven'

uploadArchives {
repositories {
mavenDeployer {
repository(url: 'file:https://' + System.properties['user.home'] + '/.m2/repository')

pom.project {
name = "Android Weak Handler"
groupId = 'com.badoo.mobile'
artifactId = 'android-weak-handler'
version = project.VERSION_NAME
description = 'Memory safer implementation of android Handler'
url = 'http:https://github.com/badoo/android-weak-handler'

scm {
connection 'scm:git:http:https://github.com/badoo/android-weak-handler/'
developerConnection 'scm:git:http:https://github.com/badoo/android-weak-handler/'
url 'http:https://github.com/badoo/android-weak-handler'
}

licenses {
license {
name 'MIT License'
url 'http:https://opensource.org/licenses/MIT'
}
}

developers {
developer {
id 'zloy'
name 'Dmytro Voronkevych'
email '[email protected]'
}
}
}
}
}
}
178 changes: 178 additions & 0 deletions src/androidTest/java/com/badoo/mobile/util/WeakHandlerTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
/*
* Copyright (c) 2014 Badoo Trading Limited
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.badoo.mobile.util;

import android.os.HandlerThread;
import android.os.SystemClock;

import junit.framework.TestCase;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
* Unit tests for {@link com.badoo.mobile.util.WeakHandler}
*
* Created by Dmytro Voronkevych on 17/06/2014.
*/
public class WeakHandlerTest extends TestCase {

public void testChainedRef() {
final Runnable runHead = new DummyRunnable();
final Runnable runFirst = new DummyRunnable();
final Runnable runSecond = new DummyRunnable();

WeakHandler.ChainedRef refHead = new WeakHandler.ChainedRef(runHead) {
@Override
public String toString() {
return "refHead";
}
};
WeakHandler.ChainedRef first = new WeakHandler.ChainedRef(runFirst) {
@Override
public String toString() {
return "first";
}
};
WeakHandler.ChainedRef second = new WeakHandler.ChainedRef(runSecond) {
@Override
public String toString() {
return "second";
}
};

refHead.insertAbove(first);
refHead.insertAbove(second);

assertSame(second, refHead.next);
assertSame(first, refHead.next.next);
assertNull(refHead.next.next.next);

assertNull(refHead.prev);
assertSame(second, first.prev);
assertSame(refHead, second.prev);

assertSame(second, refHead.findForward(runSecond));
assertSame(first, refHead.findForward(runFirst));
assertSame(refHead, refHead.findForward(runHead));
assertNull(refHead.findForward(new DummyRunnable()));

second.remove();
assertNull(second.prev);
assertNull(second.next);
assertNull(refHead.prev);
assertNull(first.next);
assertSame(first, refHead.next);
assertSame(refHead, first.prev);

assertSame(first, refHead.findForward(runFirst));
assertSame(refHead, refHead.findForward(runHead));
assertNull(refHead.findForward(runSecond));

first.remove();
assertSame(WeakHandler.ChainedRef.sPool, first); // It was put in pull
assertSame(second, first.next);
assertNotSame(refHead, first.next);
assertNull(first.prev);
assertNull(refHead.next);
}

public void testChainedRefAlloc() {
WeakHandler.ChainedRef.sPool = null;
WeakHandler.ChainedRef.sPoolSize = 0;

WeakHandler.ChainedRef ref1 = WeakHandler.ChainedRef.obtain(null);
assertNotNull(ref1);
assertEquals(0, WeakHandler.ChainedRef.sPoolSize);
WeakHandler.ChainedRef ref2 = WeakHandler.ChainedRef.obtain(null);
assertNotNull(ref2);
assertNotSame(ref1, ref2);
assertEquals(0, WeakHandler.ChainedRef.sPoolSize);
ref1.remove();
assertEquals(1, WeakHandler.ChainedRef.sPoolSize);
ref2.remove();
assertEquals(2, WeakHandler.ChainedRef.sPoolSize);
assertSame(ref2, WeakHandler.ChainedRef.obtain(null));
assertEquals(1, WeakHandler.ChainedRef.sPoolSize);
assertSame(ref1, WeakHandler.ChainedRef.obtain(null));
assertEquals(0, WeakHandler.ChainedRef.sPoolSize);
}

public void testPostDelayed() throws InterruptedException {
HandlerThread thread = new HandlerThread("test");
thread.start();

final CountDownLatch latch = new CountDownLatch(1);

WeakHandler handler = new WeakHandler(thread.getLooper());

long startTime = SystemClock.elapsedRealtime();
final AtomicBoolean executed = new AtomicBoolean(false);
handler.postDelayed(new Runnable() {
@Override
public void run() {
executed.set(true);
latch.countDown();
}
}, 300);

latch.await(1, TimeUnit.SECONDS);
assertTrue(executed.get());

long elapsedTime = SystemClock.elapsedRealtime() - startTime;
assertTrue(elapsedTime <= 305 && elapsedTime >= 300);
thread.getLooper().quit();
}

public void testRemoveCallbacks() throws InterruptedException {
HandlerThread thread = new HandlerThread("test");
thread.start();

final CountDownLatch latch = new CountDownLatch(1);

WeakHandler handler = new WeakHandler(thread.getLooper());

long startTime = SystemClock.elapsedRealtime();
final AtomicBoolean executed = new AtomicBoolean(false);
Runnable r = new Runnable() {
@Override
public void run() {
executed.set(true);
latch.countDown();
}
};
handler.postDelayed(r, 300);
handler.removeCallbacks(r);
latch.await(1, TimeUnit.SECONDS);
assertFalse(executed.get());

long elapsedTime = SystemClock.elapsedRealtime() - startTime;
assertTrue(elapsedTime > 300);
thread.getLooper().quit();
}

private class DummyRunnable implements Runnable {
@Override
public void run() {
}
}
}
5 changes: 5 additions & 0 deletions src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<manifest package="com.badoo.mobile.util">

<application />

</manifest>
Loading

0 comments on commit cdd3c94

Please sign in to comment.