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
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 have a bunch of async functions in java that I want to test. I would like to have a functionality where the main thread waits until all the tests are done. The method signature of these functions looks like as follows
public class Callback {
public void onSucess(Result result) {
return result.getLastName();
}
}
public class client{
public static void getLastNameAsync(String firstname, Callback cb);
public static void getLastNameAsync(String middlename, Callback cb);
...................................
...................................
...................................
Imagine there are more functions like this
}
I want to be be able to test the client class as follows
public void TestClient(){
Client client = new Client();
client.getLastNameAsync("Brandon", new callback());
client.getLastNameAsync("kyle", new callback());
....................
....................
....................
Imagine I have to test more functions like this
}
countDownLatch seems to be a solution however I need to know the number of method calls I am invoking and even if I do that seems to be a hacky solution because I need to instantiate as below
CountDownLatch latch = new CountDownLatch(#number of methods calls in my TestClient);
The trick again here is knowing #number of methods calls in my TestClient
open to any kind of advice or solution.
Static methods are not your friend. I would use instance classes, and then use an Executor as the means to control whether the execution is synchronous or asynchronous.
For your production code, inject a ThreadPoolExecutor in order for your logic to defer to another thread (or threads). But, in your test case, use a DirectExecutor to execute the logic in the same thread. See the javadoc for java.util.concurrent.Executor
This way, your test code will be far simpler. I'm sure you want to test the logic being called. If you need to test the multi-threadedness of it, you can then start to approach that as well. But if you don't have to, then keeping things simple will help in the test. And static methods don't help with that.
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
According to the available documentation the app engine test helper class LocalServiceTestHelper can simulate the result from ApiProxy.getCurrentEnvironment().getRemainingMillis().
This all works fine as long as the code runs in the same thread as the helper is created but is seems that when the the test is multithreaded (such as when testing a Deferred task) the second thread will not use the simulated response.
How do a get the helper class to set the return value of ApiProxy.getCurrentEnvironment().getRemainingMillis() in a task queue task?
Calling LocalServiceTestHelper.setUp() will only set your environment in the current thread, as you found.
After calling setUp(), you should be able to get the just-set environment using ApiProxy.Environment testEnv = ApiProxy.getCurrentEnvironment();wrap testEnv in an implementation of ApiProxy.EnvironmentFactory which always returns testEnv. Then, call ApiProxy.setEnvironmentFactory, passing in that new factory.
final ApiProxy.Environment testEnv = ApiProxy.getCurrentEnvironment();
ApiProxy.setEnvironmentFactory(new ApiProxy.EnvironmentFactory() {
#Override
public ApiProxy.Environment newEnvironment() { return testEnv; }
};
This should result in the same environment being used in all threads.
This approach is untested, but looks reasonable according to the doc.
I'm trying to execute some task periodically using guava AbstractScheduledService :
public class MyService extends AbstractScheduledService {
public MyService() {
}
#Override
protected void runOneIteration() {
doStuff();
}
private void doStuff() {
// Do stuff
}
#Override
protected Scheduler scheduler() {
return Scheduler.newFixedRateSchedule(0, 8, TimeUnit.HOURS);
}
}
So this service should execute some task periodically every 8 hours but it never actually does. The inherited isRunning() method returns false and the runOneIteration() method never gets invoked.
I have managed to make it work by calling the startAsync() method (inherited from parent class) from my service constructor but I don't see any reference saying this is the way it should work.
Have I missed something here? Is this the way the AbstractScheduledService works?
AbstractScheduledServiced implements Service. The Service interface describes lifecycle methods including startAsync. The ServiceState enum literals contain documentation on what they mean. A Service in NEW state (just created):
A service in this state is inactive. It does minimal work and consumes minimal resources.
For the Service to do something useful you have to transition it to the state RUNNING
A service in this state is operational.
That's why you have to start the Service before it does anything.
I would also advise against calling startAsync from the constructor and instead calling it from the Code that creates your MyService instance. It is rarely an expected thing to have such heavy side effects (creation of Threads) in the constructor.