I want to run some Extension Methods in Synchronous Task

I want to run some Extension Methods in Synchronous Task .
Can i use Multi Threading or any other option ?

i try and its working ... but as soon as it works app kills ?


package com.lucy;
import com.google.appinventor.components.annotations.*;
import com.google.appinventor.components.common.ComponentCategory;
import com.google.appinventor.components.runtime.AndroidNonvisibleComponent;
import com.google.appinventor.components.runtime.AndroidViewComponent;
import com.google.appinventor.components.runtime.ComponentContainer;
import com.google.appinventor.components.runtime.EventDispatcher;
import com.google.appinventor.components.runtime.util.YailList;

import java.util.ArrayList;
import java.util.List;

@DesignerComponent(version = 1,
                   description = "Threading",
                   category = ComponentCategory.EXTENSION,
                   nonVisible = true,
                   iconName = "images/extension.png")
@SimpleObject(external = true)

public class Lucy extends AndroidNonvisibleComponent {

public Lucy(ComponentContainer container){
        super(container.$form());
    }

public String threadStatuss = "";

 @SimpleFunction(description = "")
public void texter() {

threadStatuss = "Here is My Sync Thread Code ???";
afterThreadResult(threadStatuss);

}


 @SimpleEvent(description = "Event after ClearTable")
public void afterThreadResult(String x) {
EventDispatcher.dispatchEvent(this, "afterThreadResult", x);
}

@SimpleFunction(description = "Threded Functon")
public void threadingProcess(){

       Thread thread1 = new Thread() {
          public void run() {
          texter();

          }
       };
       thread1.start();
    }
}

How to Start / Stop / Interrupt Thread ?

I'll recommend you to open a new topic for it.

when three client device call single method on same time. Exactly at same time at fraction of seconds. I think this will produce Runtime Error.

what is solution for this ?

For this you need to use sync-locks to achieve thread safety and sequential execution.

  public final Object lock = new Object();

  public void myMethod() {
    synchronized(lock) {
      // Only one instance of the code can run at a time here
    }
  } 
  

Now when two threads call myMethod() at the exact same time, the last one to make a call will have to 'wait' before the first execution is completed.

Here we use an object lock as a unique key identifier.

Also check out java package java.util.concurrent.* that helps you write concurrent programs.

1 Like

Also my advise to you would be to not jump into high level stuff this early, you have a lot to learn, start with simpler programming topics.

You Are Right !

but what is reason this is killing app ?

how to use ????
import android.os.AsyncTask;

Currently This is Working Tested Now.

@SimpleFunction(description = "Threded Functon")
      public void onSuccess() {
        form.runOnUiThread(new Runnable() {
          @Override
          public void run() {
          texter() ;
          }
        });
      }

This code will run function on UI/Main thread. If function is a long running operation then app will get freezed until operation is completed.

Use AsynchUtil to run a function in background thread and the post result to main thread using form.runOnUiThread() .

1 Like

How to use AsynchUtil ? any Tutorial code ?

But We know that Thread means Parallel Process or Function.Then Why App UI will Freeze. I am Using Thread for Sorting Freezing Problem. :smile: :sweat_smile: :laughing:

Is this is correct way to use as following ?

import com.google.appinventor.components.runtime.util.AsynchUtil;

 AsynchUtil.runAsynchronously(new Runnable() {
      @Override
      public void run() {
       myMethod();
      }
      });

See source code of web component. Here is a sample code from my personal extension with concurrent package

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class FileHelper extends AndroidNonvisibleComponent {

    private final ExecutorService executor = Executors.newSingleThreadExecutor();

    public FileHelper(ComponentContainer container) {
        super(container.$form());
    }
// Part of code after skipping some code

@SimpleFunction(description = "Creates a new file on server.")
    public void CreateFile(String bucketId, String fileId, String projectId, String cookie, String filePath, YailList permissionsYailList) {
        executor.execute(() -> {
            try {
                // Again some code here...

                OutputStream outputStream = connection.getOutputStream();
                DataOutputStream request = new DataOutputStream(outputStream);

                // Include the fileId as part of the request
                writeFormField(request, "fileId", fileId, boundary);
                writeFileField(request, "file", new java.io.File(filePath), boundary);

                // Include permissions if specified
                if (permissionsYailList != null) {
                    for (Object permission : permissionsYailList.toArray()) {
                        writeFormField(request, "permissions[]", permission.toString(), boundary);
                    }
                }
                
                request.writeBytes("--" + boundary + "--\r\n");
                request.flush();
                request.close();

                int responseCode = connection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_CREATED) {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    reader.close();
                    form.runOnUiThread(() -> FileCreated(response.toString(), responseCode));
                } else {
                    String errorMsg = readErrorResponse(connection);
                    form.runOnUiThread(() -> ReportError("HTTP Error: " + responseCode + " - " + errorMsg));
                }

            } catch (Exception e) {
                e.printStackTrace();
                form.runOnUiThread(() -> ReportError("Failed to create file: " + e.getMessage()));
            }
        });
    }
// Other Code Continues......

That's right.

1 Like
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class FileHelper extends AndroidNonvisibleComponent {

    private final ExecutorService executor = Executors.newSingleThreadExecutor();

    public FileHelper(ComponentContainer container) {
        super(container.$form());
    }
// Part of code after skipping some code

@SimpleFunction(description = "That Simple Right ?.")
    public void CreateFile() {
        executor.execute(() -> {
        
        muMethod();
        // My concurrent Methods .
        
        
        });
    }

can i use concurreny ... again for following problem ?

image

What do you want to achieve? Can you elaborate?

I think all Solution are right !

image

but chek this diagram . simple issue is

simply if myMethod( ); is calling from same device there is no need to worry.

if myMethod( ); is calling from 50+ client device in network. it would like deadlock for that method. and data of method may misbehave. so i am Clearing this future concept.

Also there is chances of Terminating app Automatically ?

There is no way to identify whether server is busy delivering data or not.

If you are dealing with server, then you should write an async cloud function, so when 10 users request a resource they will get the resource based on their position in the line. Though it will delay the response time but will not overload server.

1 Like