简体   繁体   中英

How to handle computationally heavy objects creations

In the app I'm working on, there is a background task which does some heavy work. This task needs to be executed often, and involves a computationally heavy creation of some objects. Now, I understand that it would be better not to create these objects every time the task is ran, but to keep them as static members.

This is how I was planning to do this:

  1. The task is a Service , which is started in the onCreate method of an Application class

  2. Once the Service is started, the heavy objects are initialized

  3. When the task needs to be ran, bindService is called on the service

Is this a good way of doing this? Is there a better one?

The problem that a Service runs on the Main thread. So your scheme will not work as you wish. I would recommend you to create separate class which will create your objects.

public class HeavyObjectsHolder {

    private static volatile Object[] heavyObjects;

    public static Object[] get(){
        return heavyObjects;
    }

    public static void create(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                //creation of heavy objects
                heavyObjects = new Object[]{
                    //populating array
                };
            }
        }).start();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM