jhy/jsoup — Issue #132: OutOfMemory on Android when parsing in a loop
Author: Balaret
Created: 2011-10-12 11:27:41+00:00
State: open

This code generate OutOfMemory Exception on Android platform
Looks like a memory leak in a cycle parsing.
Android has a 16Mb heap limit so this will not happened on a desktop JVM
------------
package test.OOM;

import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import static android.widget.LinearLayout.LayoutParams.*;
import static java.lang.System.out;

public class OOM_Test extends Activity {
static final int REPEAT = 5;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout l = new LinearLayout(this);
l.setLayoutParams(new LinearLayout.LayoutParams(FILL_PARENT, FILL_PARENT));
Button b = new Button(this);
b.setText("Start tests");
b.setLayoutParams(new LinearLayout.LayoutParams(FILL_PARENT, WRAP_CONTENT));
b.setPadding(50, 5, 50, 5);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new OOM_Runnable()).start();
}});

l.addView(b);
setContentView(l);
}

public static class OOM_Runnable implements Runnable {
@Override
public void run() {
try {
for (int i = 0; i < REPEAT; i++) {
URL url = new URL("http://www.cian.ru/cat.php");
HttpURLConnection req = (HttpURLConnection)url.openConnection();
req.setRequestMethod("POST");
req.setDoOutput(true);
req.connect();
OutputStreamWriter post = new OutputStreamWriter(req.getOutputStream());
post.write("currency=2&obl_id=1&order=4&room0=1&room4=1&room3=1&room2=1&room1=1&metro[]=200&deal_type=1");
post.flush();
Document doc = Jsoup.parse(req.getInputStream(), null, url.toString());
req.disconnect();
out.println(doc.title());
}
} catch (Exception e) {}
}
}
}