1

I am wondering if there is a good way to return an object from a running thread. In my android project (not important for the question) I have this method:

public void getFolders()
{
    Thread t = new Thread(new Runnable() 
    {
        @Override
        public void run() 
        {
            List<File> result = new ArrayList<File>();
            Files.List request = null;

            do 
            {
                try 
                {
                    request = service.files().list();
                    request.setQ("'appdata' in parents");

                    FileList files = request.execute();

                    result.addAll(files.getItems());
                    request.setPageToken(files.getNextPageToken());
                } 
                catch (IOException e) 
                {
                    System.out.println("An error occurred: " + e);
                    request.setPageToken(null);
                }
            } 
            while (request.getPageToken() != null && request.getPageToken().length() > 0);
        }   
    });

    t.start();
}

This method grabs some data from the internet and store the result in List<File> result. That's why I do not want to run it in the UI thread. Now I want to return this List to my main method. What is the best way to do this?

Joel
  • 4,732
  • 9
  • 39
  • 54
Cilenco
  • 6,951
  • 17
  • 72
  • 152

2 Answers2

5
public interface Callable<V>

A task that returns a result and may throw an exception. Implementors define a single method with no arguments called call.

The Callable interface is similar to Runnable, in that both are designed for classes whose instances are potentially executed by another thread. A Runnable, however, does not return a result and cannot throw a checked exception.

How to use Callable.

EDIT: Also you should be using AsyncTask in android for doing background tasks and not create threads of your own.

Community
  • 1
  • 1
Narendra Pathai
  • 41,187
  • 18
  • 82
  • 120
  • Thank you for that! But I have three methods which looks like the above. How should I use it then? – Cilenco Sep 14 '13 at 16:24
1

You should use Callable interface instead of Runnable interface to create threads. Callable interface offers a call() method, which can return an Object.

Because you cannot pass a Callable into a Thread to execute, you instead use the ExecutorService to execute the Callable object. The service accepts Callable objects to run by way of the submit() method:

  <T> Future<T> submit(Callable<T> task)

As the method definition shows, submitting a Callable object to the ExecutorService returns a Future object. The get() method of Future will then block until the task is completed.

You can follow the sample on this link and customize it according to your requirement:

https://blogs.oracle.com/CoreJavaTechTips/entry/get_netbeans_6

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136