#what's the correct way to pass data between threads?

1 messages · Page 1 of 1 (latest)

lilac hamlet
#

context: i'm taking a class this semester for Android dev, and we're building a small game as a project but we're not allowed to use any external libraries for anything, including HTTP stuff. instead, they've given us this class to use (we need to fetch data from an API that the school has built)

the idea is that we subclass it, and pass the activity in (cont.) and when the service responds it calls a method on the activity to get the data.

is there any way to write this such that the activity itself doesn't need to be passed in? i've never done multithreading work like this before

grizzled spruceBOT
#

<@&987246964494204979> please have a look, thanks.

#

Here is an AI assisted attempt to answer your question 🤖. Maybe it helps! In any case, a human is on the way 👍. To continue talking to the AI, you can use </chatgpt:1108714622413963314>.

#
TJ-Bot
Context: i'm taking a class this semester for Android dev, and we're building a small game as a project but we're not allowed to use any external libraries for anything, including HTTP stuff. instead, they've given us this class to use (we need to fetch da

ibraries.

In Java, the correct way to pass data between threads is by using the classes provided in the Java concurrency package. One common method is using the java.util.concurrent package, which provides classes like Executor, Callable, and Future for managing thread execution and data exchange.

One approach is to use a Callable object to represent the task that needs to be executed in a separate thread. The Callable object can return a result, which can be accessed through a Future object once the task is completed. This allows for passing data between threads without directly accessing shared variables.

Another method is using ExecutorService, which manages a pool of threads for executing tasks concurrently. By submitting Callable objects to an ExecutorService, you can pass data between threads and control the execution of tasks.

It's important to ensure proper synchronization when passing data between threads to avoid race conditions and ensure thread safety. Using synchronized blocks or classes like AtomicInteger can help prevent issues with concurrent access to shared resources.

Overall, understanding how to use the concurrency classes provided in Java will help you effectively pass data between threads in your Android development projects without relying on external libraries.

lilac hamlet
#
public abstract class HttpThread {
    Activity activity;
    private String urlString ;
    String data = "";

    public HttpThread(String url, Activity activity){
        this.activity = activity;
        this.urlString = url;
    }

    public abstract void callResult(String data); //Call Back method, pass url contents to UI Thread
    public void fetchPage(){
        Thread thread = new Thread(new Runnable(){
            @Override
            public void run() {
                try {
                    URL url = new URL(urlString);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    // Starts the query
                    conn.connect();

                    InputStream inputStream = conn.getInputStream();
                    BufferedReader bufferedReader =
                            new BufferedReader(new InputStreamReader(inputStream));
                    String line = "";
                    while((line = bufferedReader.readLine()) != null)
                        data += line;
                    inputStream.close();
               activity.runOnUiThread(new Runnable() {
                        public void run() {
                            callResult(data); //Call Back
                        }
                     });
               Log.d("Background =>", " " + data);
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.d("Thread Error", e.getMessage());
                }
            }
        });
        thread.start();
    }

}```
grizzled spruceBOT
# lilac hamlet ```java public abstract class HttpThread { Activity activity; private St...

Detected code, here are some useful tools:

Formatted code
public abstract class HttpThread {
  Activity activity;
  private String urlString;
  String data = "";
  public HttpThread(String url, Activity activity) {
    this .activity = activity;
    this .urlString = url;
  }
  public abstract void callResult(String data);
  //Call Back method, pass url contents to UI Thread
  public void fetchPage() {
    Thread thread = new Thread(new Runnable() {
      @Override
      public void run() {
        try {
          URL url = new URL(urlString);
          HttpURLConnection conn = (HttpURLConnection) url.openConnection();
          conn.setRequestMethod("GET");
          // Starts the query
          conn.connect();
          InputStream inputStream = conn.getInputStream();
          BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
          String line = "";
          while ((line = bufferedReader.readLine()) != null ) data += line;
          inputStream.close();
          activity.runOnUiThread(new Runnable() {
            public void run() {
              callResult(data);
              //Call Back
            }
          }
          );
          Log.d("Background =>", " " + data);
        } catch (Exception e) {
          e.printStackTrace();
          Log.d("Thread Error", e.getMessage());
        }
      }
    }
    );
    thread.start();
  }
}
rugged dome
#

the concurrent package has queues

#

or you can use volatile shared variables if ur a chad

#

but dont do that (probably)

lilac hamlet
#

so instead of passing an activity in, you pass a queue (or the reference to one, rather) in?

eager summit
#

It's a sort of "one shot" queue

lilac hamlet
#

are futures anything like the ones in JS/Node?

#

er wait i think i might be confusing them with promises

steep mulch
#

CompletableFutures in Java are similar to Promises in JS