Can android handler leak only happen if postDelayed() is used? - android-studio

I'm still a bit confused about memory leaks in Android handlers. Android Studio seems to warn about possible memory leaks with any non-static handler, but all the examples use postDelayed() either explicitly or implicitly.
I have code that looks like this
public class MyActivity extends Activity {
public boolean handlerIsDone = false;
private MyHandler handler = new Myhandler(getContentResolver());
private class MyHandler extends AsyncQueryhandler {
public QueryHandler(ContentResolver cr) { super(cr); }
protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
...
mActivity.handlerIsDone = true;
}
}
protected void onCreate(Bundle icicle) {
Activity mActivity = this;
handler.startQuery(...);
}
...
}
I haven't checked that this compiles, it's just to show the structure. In the real app, both Activity and MyHandler do other stuff. When the activity is destroyed, both it and handler still hold references to each other, but there is no reference to handler in the message queue, or anywhere else outside the activity. Is the Android garbage collector smart enough to free the memory of both of them?
If so, why doesn't Android Studio warn just on uses of postDelayed(), rather than on every non-static handler declaration? This type of handler usage is a very common Android paradigm to get some slow-running code out of the UI thread, and it isn't very helpful to get a warning when there is actually nothing wrong with it.

Related

New Thread doesn't open scene [duplicate]

I'm trying to understand how threads works in java. This is a simple database request that returns a ResultSet. I'm using JavaFx.
package application;
import java.sql.ResultSet;
import java.sql.SQLException;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
public class Controller{
#FXML
private Button getCourseBtn;
#FXML
private TextField courseId;
#FXML
private Label courseCodeLbl;
private ModelController mController;
private void requestCourseName(){
String courseName = "";
Course c = new Course();
c.setCCode(Integer.valueOf(courseId.getText()));
mController = new ModelController(c);
try {
ResultSet rs = mController.<Course>get();
if(rs.next()){
courseCodeLbl.setText(rs.getString(1));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// return courseName;
}
public void getCourseNameOnClick(){
try {
// courseCodeLbl.setText(requestCourseName());
Thread t = new Thread(new Runnable(){
public void run(){
requestCourseName();
}
}, "Thread A");
t.start();
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
This returns an exception:
Exception in thread "Thread A" java.lang.IllegalStateException: Not on FX application thread; currentThread = Thread A
How do I correctly implement threading so that every database request is executed in a second thread instead of the main thread?
I've heard of implementing Runnable but then how do I invoke different methods in run method?
Never worked with threading before but I thought it's time for it.
Threading Rules for JavaFX
There are two basic rules for threads and JavaFX:
Any code that modifies or accesses the state of a node that is part of a scene graph must be executed on the JavaFX application thread. Certain other operations (e.g. creating new Stages) are also bound by this rule.
Any code that may take a long time to run should be executed on a background thread (i.e. not on the FX Application Thread).
The reason for the first rule is that, like most UI toolkits, the framework is written without any synchronization on the state of elements of the scene graph. Adding synchronization incurs a performance cost, and this turns out to be a prohibitive cost for UI toolkits. Thus only one thread can safely access this state. Since the UI thread (FX Application Thread for JavaFX) needs to access this state to render the scene, the FX Application Thread is the only thread on which you can access "live" scene graph state. In JavaFX 8 and later, most methods subject to this rule perform checks and throw runtime exceptions if the rule is violated. (This is in contrast to Swing, where you can write "illegal" code and it may appear to run fine, but is in fact prone to random and unpredictable failure at arbitrary time.) This is the cause of the IllegalStateException you are seeing: you are calling courseCodeLbl.setText(...) from a thread other than the FX Application Thread.
The reason for the second rule is that the FX Application Thread, as well as being responsible for processing user events, is also responsible for rendering the scene. Thus if you perform a long-running operation on that thread, the UI will not be rendered until that operation is complete, and will become unresponsive to user events. While this won't generate exceptions or cause corrupt object state (as violating rule 1 will), it (at best) creates a poor user experience.
Thus if you have a long-running operation (such as accessing a database) that needs to update the UI on completion, the basic plan is to perform the long-running operation in a background thread, returning the results of the operation when it is complete, and then schedule an update to the UI on the UI (FX Application) thread. All single-threaded UI toolkits have a mechanism to do this: in JavaFX you can do so by calling Platform.runLater(Runnable r) to execute r.run() on the FX Application Thread. (In Swing, you can call SwingUtilities.invokeLater(Runnable r) to execute r.run() on the AWT event dispatch thread.) JavaFX (see later in this answer) also provides some higher-level API for managing the communication back to the FX Application Thread.
General Good Practices for Multithreading
The best practice for working with multiple threads is to structure code that is to be executed on a "user-defined" thread as an object that is initialized with some fixed state, has a method to perform the operation, and on completion returns an object representing the result. Using immutable objects, in particular, a record, for the initialized state and computation result is highly desirable. The idea here is to eliminate the possibility of any mutable state being visible from multiple threads as far as possible. Accessing data from a database fits this idiom nicely: you can initialize your "worker" object with the parameters for the database access (search terms, etc). Perform the database query and get a result set, use the result set to populate a collection of domain objects, and return the collection at the end.
In some cases it will be necessary to share mutable state between multiple threads. When this absolutely has to be done, you need to carefully synchronize access to that state to avoid observing the state in an inconsistent state (there are other more subtle issues that need to be addressed, such as liveness of the state, etc). The strong recommendation when this is needed is to use a high-level library to manage these complexities for you.
Using the javafx.concurrent API
JavaFX provides a concurrency API that is designed for executing code in a background thread, with API specifically designed for updating the JavaFX UI on completion of (or during) the execution of that code. This API is designed to interact with the java.util.concurrent API, which provides general facilities for writing multithreaded code (but with no UI hooks). The key class in javafx.concurrent is Task, which represents a single, one-off, unit of work intended to be performed on a background thread. This class defines a single abstract method, call(), which takes no parameters, returns a result, and may throw checked exceptions. Task implements Runnable with its run() method simply invoking call(). Task also has a collection of methods which are guaranteed to update state on the FX Application Thread, such as updateProgress(...), updateMessage(...), etc. It defines some observable properties (e.g. state and value): listeners to these properties will be notified of changes on the FX Application Thread. Finally, there are some convenience methods to register handlers (setOnSucceeded(...), setOnFailed(...), etc); any handlers registered via these methods will also be invoked on the FX Application Thread.
So the general formula for retrieving data from a database is:
Create a Task to handle the call to the database.
Initialize the Task with any state that is needed to perform the database call.
Implement the task's call() method to perform the database call, returning the results of the call.
Register a handler with the task to send the results to the UI when it is complete.
Invoke the task on a background thread.
For database access, I strongly recommend encapsulating the actual database code in a separate class that knows nothing about the UI (Data Access Object design pattern). Then just have the task invoke the methods on the data access object.
So you might have a DAO class like this (note there is no UI code here):
public class WidgetDAO {
// In real life, you might want a connection pool here, though for
// desktop applications a single connection often suffices:
private Connection conn ;
public WidgetDAO() throws Exception {
conn = ... ; // initialize connection (or connection pool...)
}
public List<Widget> getWidgetsByType(String type) throws SQLException {
try (PreparedStatement pstmt = conn.prepareStatement("select * from widget where type = ?")) {
pstmt.setString(1, type);
ResultSet rs = pstmt.executeQuery();
List<Widget> widgets = new ArrayList<>();
while (rs.next()) {
Widget widget = new Widget();
widget.setName(rs.getString("name"));
widget.setNumberOfBigRedButtons(rs.getString("btnCount"));
// ...
widgets.add(widget);
}
return widgets ;
}
}
// ...
public void shutdown() throws Exception {
conn.close();
}
}
Retrieving a bunch of widgets might take a long time, so any calls from a UI class (e.g a controller class) should schedule this on a background thread. A controller class might look like this:
public class MyController {
private WidgetDAO widgetAccessor ;
// java.util.concurrent.Executor typically provides a pool of threads...
private Executor exec ;
#FXML
private TextField widgetTypeSearchField ;
#FXML
private TableView<Widget> widgetTable ;
public void initialize() throws Exception {
widgetAccessor = new WidgetDAO();
// create executor that uses daemon threads:
exec = Executors.newCachedThreadPool(runnable -> {
Thread t = new Thread(runnable);
t.setDaemon(true);
return t ;
});
}
// handle search button:
#FXML
public void searchWidgets() {
final String searchString = widgetTypeSearchField.getText();
Task<List<Widget>> widgetSearchTask = new Task<List<Widget>>() {
#Override
public List<Widget> call() throws Exception {
return widgetAccessor.getWidgetsByType(searchString);
}
};
widgetSearchTask.setOnFailed(e -> {
widgetSearchTask.getException().printStackTrace();
// inform user of error...
});
widgetSearchTask.setOnSucceeded(e ->
// Task.getValue() gives the value returned from call()...
widgetTable.getItems().setAll(widgetSearchTask.getValue()));
// run the task using a thread from the thread pool:
exec.execute(widgetSearchTask);
}
// ...
}
Notice how the call to the (potentially) long-running DAO method is wrapped in a Task which is run on a background thread (via the accessor) to prevent blocking the UI (rule 2 above). The update to the UI (widgetTable.setItems(...)) is actually executed back on the FX Application Thread, using the Task's convenience callback method setOnSucceeded(...) (satisfying rule 1).
In your case, the database access you are performing returns a single result, so you might have a method like
public class MyDAO {
private Connection conn ;
// constructor etc...
public Course getCourseByCode(int code) throws SQLException {
try (PreparedStatement pstmt = conn.prepareStatement("select * from course where c_code = ?")) {
pstmt.setInt(1, code);
ResultSet results = pstmt.executeQuery();
if (results.next()) {
Course course = new Course();
course.setName(results.getString("c_name"));
// etc...
return course ;
} else {
// maybe throw an exception if you want to insist course with given code exists
// or consider using Optional<Course>...
return null ;
}
}
}
// ...
}
And then your controller code would look like
final int courseCode = Integer.valueOf(courseId.getText());
Task<Course> courseTask = new Task<Course>() {
#Override
public Course call() throws Exception {
return myDAO.getCourseByCode(courseCode);
}
};
courseTask.setOnSucceeded(e -> {
Course course = courseTask.getCourse();
if (course != null) {
courseCodeLbl.setText(course.getName());
}
});
exec.execute(courseTask);
The API docs for Task have many more examples, including updating the progress property of the task (useful for progress bars..., etc.
Related
JavaFX - Background Thread for SQL Query
Sample for accessing a local database from JavaFX using concurrent tasks for database operations so that the UI remains responsive.
Exception in thread "Thread A" java.lang.IllegalStateException: Not on FX application thread; currentThread = Thread A
The exception is trying to tell you that you are trying to access JavaFX scene graph outside the JavaFX application thread. But where ??
courseCodeLbl.setText(rs.getString(1)); // <--- The culprit
If I can't do this how do I use a background thread?
The are different approaches which leads to similar solutions.
Wrap you Scene graph element with Platform.runLater
There easier and most simple way is to wrap the above line in Plaform.runLater, such that it gets executed on JavaFX Application thread.
Platform.runLater(() -> courseCodeLbl.setText(rs.getString(1)));
Use Task
The better approach to go with these scenarios is to use Task, which has specialized methods to send back updates. In the following example, I am using updateMessage to update the message. This property is bind to courseCodeLbl textProperty.
Task<Void> task = new Task<Void>() {
#Override
public Void call() {
String courseName = "";
Course c = new Course();
c.setCCode(Integer.valueOf(courseId.getText()));
mController = new ModelController(c);
try {
ResultSet rs = mController.<Course>get();
if(rs.next()) {
// update message property
updateMessage(rs.getString(1));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
public void getCourseNameOnClick(){
try {
Thread t = new Thread(task);
// To update the label
courseCodeLbl.textProperty.bind(task.messageProperty());
t.setDaemon(true); // Imp! missing in your code
t.start();
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This has nothing to do with database. JavaFx, like pretty much all GUI libraries, requires that you only use the main UI thread to modify the GUI.
You need to pass the data from the database back to the main UI thread. Use Platform.runLater() to schedule a Runnable to be run in the main UI thread.
public void getCourseNameOnClick(){
new Thread(new Runnable(){
public void run(){
String courseName = requestCourseName();
Platform.runLater(new Runnable(){
courseCodeLbl.setText(courseName)
});
}
}, "Thread A").start();
}
Alternatively, you can use Task.

RxJava Observable Zip Causes Memory Leak

I am using RxJava's Observable.zip method to combine two API calls into one result. For some reason I am getting a memory leak despite the fact that I unsubscribe from the subscription. I am not sure if this a bug on my end or if there is something I need to do with the creation of the Observable.
protected void onCreate(Bundle bundle) {
...
subscription = Observable.zip(
api.getConfiguration(),
api.getSettings().map(r -> r.getData()),
new Func2<ConfigurationResponse, List<Datum>, Struct>() {
#Override
public Struct call(ConfigurationResponse config, List<Datum> data) {
return new Struct(data, config.getCopy(), config.getSettings());
}
}
)
.compose(Schedulers.applyApiSchedulers())
.subscribe(
struct -> {
configurationManager.set(struct.data, struct.copy, struct.settings);
startNextActivity();
},
error -> {
startNextActivity();
}
);
}
protected void onDestroy() {
if (!subscription.isUnsubscribed()) {
subscription.unsubscribe();
}
}
Here is the trace from Leak Canary.
Any help would be appreciated.
I suspect the leak comes from the subscription itself as you seem to keep referencing the Subscriber through it. Try clearing that reference in onDestroy and check again for leaks.
This is probably a leak in retrofit, a similar one seems to have been reported here.
Note that if retrofit leaks the subscriber, you may be able to limit the impact if your mapper func no longer references your activity instance.
In your case Struct is probably a non-static instance class (hence having an implicit reference to the activity instance), if you manage to make it static w/o referencing the activity, you'll likely get rid of this very leak.

Garbage collecting issue with Custom viewbinding in mono touch and mvvmcross

I have a custom calendar control for which there is an custom viewbinding. In this viewbinding we hook up some events which are not decoupled correct and therefor is the garbage collecting not completed. In the following is our custom view binding. As you can see the event is hooked up in the constructor and decoupled in the OnSelectedDate event is triggered(the user selects an date). Therefore if you choose a date the event is decouple correct and garbage collected but if you just go back, the event is still hooked up and no garbage collecting is performed. I thought about trigger the event with null values and and thereby decoulpe the event. But I think there must be some more clever way to achieve this.
namespace CmsApp.Core.Binders
{
public class CalendarViewBinding:MvxBaseTargetBinding
{
private CalendarView _calendarView;
private DateTime _currentValue;
public CalendarViewBinding(CalendarView calendarView)
{
_calendarView = calendarView;
_calendarView.OnDateSelected+=OnDateSelected;
}
protected override void Dispose(bool isDisposing)
{
if(_calendarView!=null)
{
_calendarView.OnDateSelected -= OnDateSelected;
_calendarView = null;
}
base.Dispose(isDisposing);
}
private void OnDateSelected(object sender, SelectedDateEventArgs args)
{
_currentValue = args.SelectedDate;
this.FireValueChanged(_currentValue);
_calendarView.OnDateSelected -= OnDateSelected;
}
public override void SetValue(object value)
{
var date = (DateTime)value;
_currentValue = date;
_calendarView.SelectedDate = _currentValue;
}
public override Type TargetType
{
get
{
return typeof(DateTime);
}
}
public override MvxBindingMode DefaultMode
{
get
{
return MvxBindingMode.TwoWay;
}
}
}
}
Any help is appreciated :)
It looks to me like your binding is almost correct.
The only issue I can see is that it unsubscribes from the event too often - you can't call _calendarView.OnDateSelected -= OnDateSelected; twice - but I don't think this is the problem you are seeing.
I currently would guess that the problem is not in the code you are using:
either there's a bug in the binding code in the underlying framework you are using
or something is a bug/issue in the way you are using this binding
or your memory leak has nothing to do with this binding
It's not easy to test this from the limited code posted here, but it would be simpler if you could produce a simple app that reproduces the leak you are seeing. Share that and you might be able to get more feedback.
If you believe my guesses are wrong, then the only thing I can suggest is that you switch to WeakReferences inside your binding - but this feels like a sticking plaster rather than a cure.
Just adding a link to when to release objects in mono touch / mvvmcross

How to update UI after a web service calling thread is finished

Questions about threads are in no shortage, I know, but I can't seem to find a "full" example of a thread doing http work and then coming back to update the UI.
I basically call a few web services upon app launch. I obviously don't want to freeze the UI so I would want to use a separate thread, right? I have found a bunch of examples online on how to get a new thread to perform some task. But I haven't yet found one that shows how to actually update the UI when the thread's task is done.
How do I know when the web service thread is done? Is there a callback method? Can I access the UI from this callback method if one exists.
Edit: (Here is some code)
//The activate method is called whenever my application gains focus.
public void activate(){
DoSomething wsThread = new DoSomething();
wsThread.start();
}
public void wsCallBack()
{
myTabScreen.add(new ButtonField("Callback called"));
}
public class DoSomething extends Thread
{
public void run()
{
try
{
wsCallBack();
}
catch(Exception e)
{
}
}
}
Very simple. But it never creates the button.
Any ideas?
Thanks a lot.
You can set up a "callback" system to notify the UI when the threads complete. Have a class that extends Thread and pass to it a reference of the class that should be called at the end. If you have a list of such classes that needs to be notified create a Vector on the Thread implementation to hold them. Override the run function and after doing everything you need to do simply call a method on the UI class (iterating through the vector if needed). So your classes may look like:
public class commThread extends Thread{
MyUIClass callbackObj;
public commThread(MyUIClass myUiClass){
callbackObj = myUiClass;
}
public void run(){
//do stuff
callbackObj.callback();
}
}
and your UI class:
public MyUIClass{
public void callback(){
//refresh the UI
}
}
Of course if you have multiple threads running at the same time and calling the same UI object make sure to synchronize the callback method.
Hope this helps!

Why would MonoTouch not garbage collect my custom UIButton unless I call button.RemoveFromSuperview()?

There seems to be something holding a reference to my custom button, MyButton (which inherits from UIButton), causing it not to be garbage collected unless I remove it from the superview. This, in turn, would cause the view controller that it is on to also not be finalized and collected.
In my example, I have my custom button but I also have a standard UIButton on the view controller which does not need to be removed from the superview in order to be collected. What's the difference? Looks pretty similar to me.
See this code. The irrelevant lines were removed for example's sake. Some things to note about the sample:
-MyButton is pretty empty. Just a constructor and nothing else overridden.
-Imagine MyViewController being on a UINavigationController
-LoadView() just creates the buttons, hooks up an event for each and adds it to the view
-Touching _button would push another MyViewController to the nav controller
-I'm doing some reference cleanup when popping view controllers off the nav controller in ViewDidAppear()
-In CleanUpRefs() you'll see that I have to remove _myButton from superview in order for all the objects to be garbage collected. _button, on the other hand does not need to be removed.
-I'm expecting the entire MyViewController to be collected, including all subviews, when popping from the nav controller but commenting out _myButton.RemoveFromSuperview() stops this from happening.
public class MyViewController : UIViewController
{
private UIButton _button;
private MyButton _myButton;
private MyViewController _nextController;
public override void LoadView()
{
base.LoadView();
_button = UIButton.FromType(UIButtonType.RoundedRect);
_button.TouchUpInside += PushNewController;
View.AddSubview(_button);
_myButton = new MyButton();
_myButton.TouchUpInside += MyButtonTouched;
View.AddSubview(_myButton);
}
private void PushNewController(object sender, EventArgs e)
{
_nextController = new MyViewController();
NavigationController.PushViewController(_nextController, true);
}
private void MyButtonTouched(object sender, EventArgs e)
{
Console.WriteLine("MyButton touched");
}
public void CleanUpRefs()
{
//_button.RemoveFromSuperview();
_myButton.RemoveFromSuperview();
// remove reference from hooking up event handler
_button.TouchUpInside -= PushNewController;
_myButton.TouchUpInside -= MyButtonTouched;
_button = null;
_myButton = null;
}
public override void ViewDidAppear(bool animated)
{
base.ViewDidAppear(animated);
if(_nextController != null)
{
_nextController.CleanUpRefs();
_nextController = null;
}
}
}
It seems as if there's something different with the fact that MyButton isn't a straight UIButton in that it is inherited. But then again, why would there be an extra reference count to it that's being removed by calling RemoveFromSuperview() especially when there's a UIButton just like it that doesn't need to be removed?
(I apologize for the really bad layout, stackoverflow seems to have problems laying out bullets right above code snippets)
Update: I filed a bug report with the MonoTouch team. You can download the sample project from there if you want to run it. Bug 92.
The reason for not garbage collecting in that scenario is just a bug in MonoTouch.
The upcoming MonoTouch release will contain a fix for this. If you are in a hurry, you can replace your /Developer/MonoTouch/usr/lib/mono/2.1/monotouch.dll with the copy I placed here:
http://tirania.org/tmp/monotouch.dll
I would make a backup, in case I did something wrong in my work-in-progress library.

Resources