When a new object from the Database arrives, a new Handler will be created which posts the object to the UI thread so that the UI processes and draws the object.
public void notify(MyObject myObject) {
Handler handler = new Handler(Looper.getMainLooper());
Runnable runnable = new Runnable() {
@Override
public void run() {
myview.handleUpdate(myObject);
}
};
handler.post(runnable);
}
This works perfectly but when 100 messages come in at a the same time, 100 threads will be created and this creates a bottleneck.
I would like to let the handler wait for 2 seconds before it starts, so it can wait for other objects.
I've tried the following but this doesn't work. The thread will be initiated but waits 2 seconds for other objects which will be added to the list. When the time is over the thread will be posted to the main thread with all the objects.
boolean wait = false;
ArrayList<MyObject> myObjectList = new ArrayList<>();
public void notify(MyObject myObject) {
if(wait) {
myObjectList.add(myObject); // handler waits already, just add the object to the list
return;
}
wait = true; // says that the handler waits for data
myObjectList.add(myObject);
Handler handler = new Handler(Looper.getMainLooper());
Runnable runnable = new Runnable() {
@Override
public void run() {
Thread.sleep(2000); // wait for 2 seconds
myview.handleUpdate(new ArrayList<>(myObjectList));
wait = false; // posted, a new handler can be created
myObjectList.clear();
}
};
handler.post(runnable);
}