Wait or Sleep...which method will be suitable?
void A()
{
//Some Code 1
some_function(); // calling a method and will seek for a response from other device, communicating on bluetooth
//Some code 2
}
I want my program to wait for the process of some_function(). However at the moment it starts executing "Some Code 2" part of function A().
And kindly if someone specify wait method implementation my case.
p.s: Async is not my priority.
Since you dint want to do async task,making the thread sleep may freeze the UI. Even if it didn't, it is still insanely bad practice.
so first thing - you have to do it on a separate thread. and Asynctask is best for it.
some_function() would be executed before //Some code 2 if it is not running on a separate thread(As you said its not Asynctask).But in case it is running on a separate thread(which it should be)-.
you can just simply call "//Some code 2" inside some_function() at the end.
OR
if you do not want to do that,try it like this-
First make an interface -
public static interface On_some_function_complete{
void onComplete(what ever parameters you want);
}
put an instance of this interface in your some_function() as parameter where ever you define it and call the onComplete method in the end of the function ,like-
void some_function(On_some_function_complete arg_on_complere){
//what ever stuff your code dose
arg_on_complere.onComplete(/*with required arguments*/);
}
now make call like -
void A()
{
//Some Code 1
some_function(new On_some_function_complete{
#Override
public void onComplete(Bitmap result) {
//Some code 2
}
});
}
OR
you must have some function that you can override to handle on-Compete action
Related
I have an OSGI bundle of a following structure:
//...
public ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
//...
#Activate
public void activate() {
executor.submit(new Runnable() {
#Override
public void run() {
//call 3 functions and log the data
}
}
}
#Deactivate
public void deactivate(){
//call 2 other functions
}
The executor in the activate method makes sure that 3 functions are called in a separate from all other bundles thread, because those functions actually implement some sophisticated Windows-message-loop, i.e. a while true loop, that's why, in order not to block other bundles, it is activated in a separate thread. Now what I've sadly noticed, that in order to run 2 functions in deactivate method I need to run them in the same thread, in which 3 functions in activate method were run. Simply speaking, I need to be sure, that activate and deactivate methods of my bundle run in the one same thread, but still to keep this bundle activation separated (in an own thread) from the other bundles.
My question is: how to implement this?
I am not a guru in concurrency in Java, I've tried simply to call this executor in the deactivate method too but I don't know how to do it with one Runnable task, since in deactivate I have only to call 2 functions and in activate only 3 functions and no other calls should be made.
UPD: sorry, I forgot to mention, that there is a routine in another bundle, which calls in certain situations context.getBundle(0).stop() in order to call a deactivation for all bundles. If I want just to add the same submit routine in the deactivate method as is in activate, then in such situation I could clearly see, that those 2 functions from deactivate method of my bundle in the submit's body were not called.
Simply do another executor.submit in deactivate. As it is a single threaded executor it will make sure only one thread processes both.
The only question is how to shut down the executor reliably. Normally after deactivate a component should have closed all its resources.
This sounds like a very common problem. I would just make it explicit you're using a thread and use the methods in Thread that were designed for this. At activate you start the thread, at deactivate you interrupt it. Your main loop watches the interrupt status and executes your deactivate functions after it is interrupted. After interrupt, it is best to join the thread to ensure your activate() method does not return before the background thread has finished running your deactivate functions.
Since exiting the framework (stopping bundle 0) must stop all bundles, and a stopped bundle will deactivate its components, this should all work.
public class Foo extends Thread {
#Activate void activate() { start(); }
#Deactivate void deactivate() throws Exception { interrupt(); join(); }
public void run() {
while(!isInterrupted()) try {
... your 3 function loop
} catch( InterruptedException e) {
break;
}
... 2 deactivate functions
}
}
I need to run a function on a complete independent thread wile the rest of my function gets executed for example
public void a(){
// do dome work
}
public void b(){
// do dome work
a()
return "hello"
}
I need my code to start ruining function a but returns hello without waiting for function a to end
I have tried task executors with spring and #Async annotation but noting is working
public static String mainMEthod() {
asyncMethodWithReturnType();
return "hello";
}
#Async
public static Future<String> asyncMethodWithReturnType() {
for (int i = 0; i < 10; i++) {
System.out.println("Execute method asynchronously - " +
Thread.currentThread().getName());
}
try {
Thread.sleep(5000);
return new AsyncResult<String>("hello world !!!!");
} catch (InterruptedException e) {
//do anything
}
return null;
}
Here is the output :
Execute method asynchronously - main
Execute method asynchronously - main
Execute method asynchronously - main
Execute method asynchronously - main
Execute method asynchronously - main
Execute method asynchronously - main
Execute method asynchronously - main
Execute method asynchronously - main
Execute method asynchronously - main
Execute method asynchronously - main
but it should not be running on the main thread
#Async has two limitations:
it must be applied to public methods only
self-invocation – calling the async method from within the same class – won’t work.
The reasons are simple – the method needs to be public so that it can be proxied. And self-invocation doesn’t work because it bypasses the proxy and calls the underlying method directly.
Also make sure to configure correctly:
#Configuration
#EnableAsync
public class SpringAsyncConfig { ... }
Read more:
https://www.baeldung.com/spring-async
The way Spring add functionalities like Async (apart from many others like this) is by creating and injecting a proxy which has the logic of providing these functionality.
In your case the call to asyncMethodWithReturnType cannot be intercepted by Spring as this is plain java method call without intermediate spring managed proxy. For more information you can check out here.
The #Async can't be run in a separate thread if the caller is within the same bean.
So option one is to move the a() method to a different bean and call it from b()
Or, consider doing what we did in our spring boot project when we needed something similar:
public void b() {
CompletableFuture.runAsync(() -> a());
return "hello";
}
I have defined this kind of Android Java class, where native function baresipStart() never terminates:
package com.tutpro.baresip;
public class BaresipThread extends Thread {
public void start() {
baresipStart();
}
public void kill() {
baresipStop();
}
public native void baresipStart();
public native void baresipStop();
}
I then call its start() function from another Java class:
BaresipThread thread;
thread = new BaresipThread();
thread.start();
The result is that baresipStart() function starts to run fine, but rest of the application becomes completely unresponsive.
Why is that and how to fix the code so that baresipStart() function runs in the background without stopping all other activity?
Thread.start() is responsible for actually creating the new thread of execution and setting it running. By overriding it as you did, you cause it to instead run baresipStart(), in the thread that invokes start().
Instead of overriding start(), you should override run(). This method is what defines the work to be performed in the new thread of execution.
Furthermore, if native method baresipStart() indeed never returns then you have a problem. Your application cannot terminate while it has any active threads. Supposing that you intend for baresipStop() to cause the thread to finish, you should arrange for baresipStart() to return (or to throw an unchecked exception) when execution is terminated by an invocation of baresipStop(). Do be aware, however, that those native methods need to be thread-safe, because they will, perforce, be invoked by different Java threads.
Thanks for your explanation. I got the new baresip thread started by removing BaresipThread object altogether and replacing the three lines above with this:
new Thread(new Runnable() {
public void run() {
baresipStart();
}
}).start();
User can stop the resulting process via its user interface after which the application is terminated.
I know it is a very question. I am trying to implement a callback mechanism.
I have a java Class in Android and inside i have an interface
public interface MyInterface {
public void cb1(Integer id);
public void cb2(Integer id);
};
User can use my Interface and implement, and whenever i need to inform to the user , i will invoke cb1() or cb2().
Question:
Let's say user have provided me implementation of interface mInterface,
while (1) {
mInterface.cb1()
}
1) In which thread cb1() will get invoked ? sync call or async call ?
2) if async call, what if the implementation of cb1() blocks for some time? Will all the cb1() calls delivered to the user one by one ?
In the code above it will be a synchronous call. If you want it to be async, you should create a new Thread to perform the callback on.
Odd question. The code will be async relative to the main thread if it is not executed on the main thread. Otherwise it will be sync and is executed on the main thread
As in the title, I want to test a method like this:
public void startThread()
{
new Thread()
{
public void run()
{
myLongProcess();
}
}.start();
}
EDIT:
Judging by comments I guess it is not very common to test if a thread starts or not. So I've to adjust the question... if my requirement is 100% code coverage do I need to test if that thread starts or not? If so do I really need an external framework?
This can be done elegantly with Mockito. Assuming the class is named ThreadLauncher you can ensure the startThread() method resulted in a call of myLongProcess() with:
public void testStart() throws Exception {
// creates a decorator spying on the method calls of the real instance
ThreadLauncher launcher = Mockito.spy(new ThreadLauncher());
launcher.startThread();
Thread.sleep(500);
// verifies the myLongProcess() method was called
Mockito.verify(launcher).myLongProcess();
}
If you need 100% coverage, you will need to call startThread which will kick off a thread. I recommend doing some sort of verification that the thread was stared (by verifying that something in myLongProcess is happening, then clean up the thread. Then you would probably do the remainder of the testing for myLongProcess by invoking that method directly from your unit test.