Is there a way to make my own asynchronous methods on GWT? I am using gwt 2.7 and seems like no java concurrency classes are compatible with gwt.
Here is my story. My client side has a service class, which caches some server data. It has a normal getter method(synchronous) to get the cached data, and it also has a reload method to update the cache.(of course, it is asynchronous). After reload request is sent, the getter method should be disabled until update is done.
Right now, each time I use the getter method, I wrap it inside a timer. It works fine, but I am wondering there is a better way to do it. It is too much boilerplate code.
final AutoProgressMessageBox messageBox =
ServiceManager.createProgressMessage("Progress", "Loading Products...");
Timer timer = new Timer(){
#Override
public void run() {
if(!serviceManager.isProductLocked()){
// already loaded
serviceManager.getProducts();
// do my work...
messageBox.hide();
this.cancel();
}
}
};
timer.scheduleRepeating(2000);
GWT has the Scheduler class, which allows you access some static methods that simulate a multithreaded environment. Specifically, you might be interested in the Scheduler.scheduleFixedPeriod method:
Schedules a repeating command that is scheduled with a constant delay. That is, the next invocation of the command will be scheduled for delayMs milliseconds after the last invocation completes.
Related
I am working on java TimerTask Scheduler Application. I have main class as Service which is running as Scheduler.
I have TaskSchedule() extends TimerTask class which is used for fixed time execution as:
timer.scheduleAtFixedRate(new TaskSchedule(), ...)
Inside constructor for TaskSchedule I have a dataHelper class which interacts with database for fetching and updating values from database.
In the TaskSchedule class I am overriding run method of TimerTask.
And inside the run method I am calling database helper call with parameters as:
#Override
public void run(){
dataHelper.fetchDataFromDB( ? )
}
Here the question I have placed, where I am stuck in design. I want to keep this parameter to database dynamic.
One Solution I though of is:
Passing database parameter throughout from service to TaskScheduler to dataHelper. But I am looking for better solution on the same at design level.
You can use a shared variable, which you can set outside and also take is before "fetchDataFromDB". You have to care of synchronization. Use a mutex to secure the shared memory.
A another solution is, that you can use somethink like a listener and every time you want to fetch from the db the listener will now it and get the data from you.
I'm a little new to AsynTasks in java programming for Android...
But, I see their point (let the UI continue while slow operations happen)
I have a GCE (Google Cloud Endpoint) API set up. To access it from the android app, it must be executed in an AsynTask according to what I've read.
My confusion lies with exactly what is the limitation within the AsyncTask before returning to onPostExecute?
The obvious use, is calling your API once.
So something like:
final myAPI.Builder builder = newmyAPI.Builder(
AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null);
builder.setApplicationName("mine");
AsyncTask<String, Void, com.appspot.myapp.myAPI.model.sample> publishAPItask =
new AsyncTask<String, Void, com.appspot.myapp.myAPI.model.sample> () {
#Override
protected com.appspot.myapp.myAPI.model.sample doInBackground(String... strings) {
// Retrieve service handle.
myAPI apiServiceHandle = CloudEndpointUtils.updateBuilder(builder).build();
try {
myMethod myMethodCommand = apiServiceHandle.sample().myMethod();
newthing.setthing(myMethodCommand.execute().getthing());
...
that last line executes, but also refers to the result already. I've read thats a no-no. Is that true? From here is a quote:
If you need to use an object that should be returned by the task, make use of the task’s onPostExecute override method. If you request a Lobster object from your API using an AsyncTask, and >then immediately try to use it in your next line of code (for example, Lobster lobster = new GetLobsterAsyncTask().execute(lobsterName); lobster.dance();), you will receive an exception. So, not only will your lobster “not dance,” it will “throw a NullPointerException at you”.
But it's a bit open to interpretation. Since I've never had an issue with the above use of the result, right away.
I seem to get intermittent issues when I added another call after the above code, calling other GCE methods within the same AsynTask - note, not using the result of the other calls.
myMethod2 meMethod2Command = apiServiceHandle.sample().myMethod2();
newthing2.setthing(myMethod2Command.execute().getthing());
So is there a hard rule somewhere that says we can only make 1 call to GCE methods per AsynTask?
Are the lines within the AsyncTask doInBackground() executed in sequence, or is it possible these GCE .execute() calls are made in parallel?
Before I rewrite a couple AsyncTasks so that they only contain 1 call each (and have a long line of onPostExecute() stacked up), I'd like to make sure I understand it...
It gets complex for me as I have a bunch of calls to make even a loop of calls. I want to make to my GCE method. So second question is: Any suggestions for making a loop of calls to GCE methods? I've also read the AsynTask can only executed once.
UPDATE: I have now just gone with the assumption that we can only make 1 GCE call per Asynctask. This makes for some interesting challenges for me, as I need to make a few in a certain circumstance in my app.
Anyway, what it turns out to be for me, is a loop of asynctasks being called, where each asynctask being called, ends up calling another loop of asynctasks within their onPostExecute.
ie. psuedocode:
loop
asynctask 1 defined {
do inbackground {
...;
}
onPostExecute {
loop
asynctask 2 defined {
doinbackground {
...;
};
onPostExecute {
};
};
asynctask2.execute;
end loop;
};
};
asynctask1.execute;
end loop;
And the real challenge now, is that I need to know when they've all completed, before doing another operation.
I've seen a couple suggestions for an array of tasks and checking their status, or calling a function to increment a count.
Let me know if you have other ideas...
--- final update
Ended up going with a thread tracker count. Before each execute above, I increment 1. In each postexecute, I decremented 1. When the tracker's count is 0, I know I can call the final operation needed.
private class threadtracker {
public int todo;
public threadtracker (String grpid) {
todo = 0;
}
public void add(int adder) {
todo = todo + adder;
Log.v(TAG, " threads:" + todo);
}
public void subtract(int subber) {
todo = todo - subber;
Log.v(TAG, " threads:" + todo);
if (todo == 0) {
//do final operation
}
}
}
(Edit: I've edited my answer based on nempoBu4's comment)
Here's some info on AppEngine Endpoints and using Endpoints in a Android client:
Udacity has a course covering App Engine it might be worth some of your time.
https://www.udacity.com/course/ud859
You should read their Android client code though and see how they consume Endpoint methods in the client. It's on GitHub. The app is called Conference Central.
https://github.com/udacity/conference-central-android-app
So is there a hard rule somewhere that says we can only make 1 call to GCE methods per AsynTask?
I don't think so, I've made multiple calls to my backend from a background thread using endpoints with no problems. The only thing I would worry about doing this in a single AsyncTask, is the amount of time it would take to complete. "AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.)" As per the Android Reference on AsyncTask.
Any suggestions for making a loop of calls to GCE methods?
I've set up an IntentService to consume endpoint methods in a background thread. It's pretty straight forward to use, just follow the developers guide. It'll put calls to the service in a queue, then once the service empties the queue it'll shut its self down. You can set up a Broadcast manager to handle results.
Good luck.
I have an onclick javascript function (invoked from DOJO components through .jsp file) within which two UI components are loaded at the same time in js file (through an AJAX call to the Spring Controller (java file) and back to the JSP/Javascript file.)
The problem is that the second component loads before the first component and is not displaying the prescribed data . I would like to know how to set a delay before calling the code in javascript to delay the second component in milliseconds.
Note :
I used Thread.sleep(msecs) in my controller which seems to work fine and resolves my issue. But I dont want to use that knowing the risk it poses. So request an alternative instead of this.
Also I used setTimeOut() function but setTimeOut() requires a function as an argument. I need to just delay the code within the function for a few milliseconds the first time only. From second time onwards I dont want to delay the code being called.
Request ur valuable inputs.
JavaScript doesn't allow blocking threads, so the only option you can use is setTimeOut() function.
Or you can implement mechanism when the first component notifies the second when it loads and at this moment the second component reloads itself.
Maybe your Problem can be solved by using http://dojotoolkit.org/reference-guide/1.8/dojo/domReady.html?highlight=domready to make sure tho dom is entirely loaded
or by using dojo/deffered
http://dojotoolkit.org/reference-guide/1.8/dojo/Deferred.html?highlight=domready
regards
Delaying the execution of code is not a good idea. In development, the calls might be executed and returned in the order you want. But in a production environment with a system under load, the timing of the server calls being executed may not be consistent.
I am assuming that you are using dojo/xhr to make the ajax calls and your solution is to use a DeferredList.
http://dojotoolkit.org/reference-guide/1.9/dojo/DeferredList.html
var d1 = xhr(...);
d2 = xhr(...);
var dl = new DeferredList([d1, d2]);
dl.then(function(result){
// Execute the code that requires both calls to be completed.
});
I am trying to get my head around session - timeout - idle handling Multi-treads in Java.
I have a server & client application comunicating via telnet where I need to check if the user has been typing (anything), clicking (anywhere), or moved the mouse within a periode of time.
If not, the user will be prompted with a dialog box, asking if he wants to conntinue session or not. ...(and If not, the user will automatically be logged out within the next minute or so.)
My application has multiple threads. ( - One user per thread). So I am not sure how to approatch this the best (and easiest) way?
I know it is a wide and far-fetched question, but I was hoping some of you could give me a pointer or tip in the right direction... :)
I was kind of hoping for a simple method that could check:
(a bit pseudo code on the fly:)
if (idle = true){
timer.start();
if (timer > 120sec)
displayWaringJFrame("Continue Session? - YES or NO ?)
displayTimer.start();
if (displayTimer > 30sec)
application.user.closeSession()
...or something like that! :)
The simplest solution is a class java.lang.Thread.
You can create class and implements interface Runnable
public class Session implements Runnable{
public void run(){
//your code
}
}
in main function create class Thread and as constuctor argument set instance of Session class after this importatnt is call method .start()
public static void main(String args[]){
new Thread(new Session()).start();
}
Much more convenient way to work with threads is java.util.concurrent.ExecutorService and java.util.concurrent.Executors
Some ideas:
1. if you want a persistent timer you can use a library like Quartz which then you can run a job class you write after a period of time. You can cancel scheduled job, re-schedule etc...
2. You don't necessarily need a thread per user for this to work. A timer object usually has internal threads to handle the workload, either with Quartz or the memory only Java timers.
I am currently working on an android app just for personal use. The app communicates with a server by TCP sockets. If the user makes an input it needs to be sent immediately. Also there can be messages from the server at any given time which need to be shown on the UI. For all the networking stuff I have a background thread in mind.
Since I need to pass messages From the UI to the networking thread at any user input and also messages from the networking thread to the UI at any given time my question follows: How can I pass the messages? I already read about the Handler class for 3hours and I couldn't figure out anything. How do handlers work? What would be a neat and smooth running implementation of that? I look more for a strategy to accomplish this goal, not necessarily implementation details.
Thank you so much in advance!
http://developer.android.com/reference/android/os/AsyncTask.html Use this I too had a lot of problems with handlers but the async task handles all that annoying work for you. Make sure you use onPrexecute() and onPostExecute() to update the UI. Hope this helps.
You can use AsyncTask in this case.
You can call it on the UI thread and in onPostExecute do what you want to do with the messages.
It is a much cleaner approach than doing all the dirty networking work there.
First, I'll say I'm learning this myself, but I've managed to get this exact setup working in a prototype. If anyone sees something that should be changed to work better in Android, by all means let me know.
Second, I'm using empty messages so that we have code that would actually work. I assume that creating message objects is straight forward enough.
Part 1 - UI to Network Thread
As far as I have seen, Handler is the answer you need, but it's not the whole picture. Deucalion's comment about Looper is where you need to look next.
http://developer.android.com/reference/android/os/Looper.html
class LooperThread extends Thread {
public Handler mHandler;
public void run() {
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};
Looper.loop();
}
}
This setup is counter intuitive at first, you need to create the Handler object between the Looper.prepare() and Looper.loop() calls, inside your run() method. I don't know the magic behind the scenes, haven't had a chance to get that far down the rabbit hole.
Important Note:
The sample shows an anonymous Handler() being created. I highly recommend subclassing Handler in your own class and then using an instance of that. It's just a matter of reusability, a lot of network code ends up being the same.
So, rename LooperThread to NetworkThread, or whatever you'd like it to be, and put your connection code in the run() method, but outside the Looper.prepare() / Looper.loop() block (again I don't know how the magic works, so I'm just assuming this is better to do than to have it inside).
// process incoming messages here
Tends to look like this:
switch(msg.what)
{
case 1:
break;
default:
break
}
The LooperThread example has public Handler mHandler; but I prefer to make the handler private and create a method to return it. I do this just to prevent the handler from being accessible until after the network connection is established. No connection, nothing to do with the messages.
So, somewhere in your activity code you create the NetworkThread object, run it, and then get the Handler from it.
NetworkThread network = new NetworkThread();
new Thread(network).run();
//Handler networkHandler = network.handler;
Handler networkHandler = network.getHandler();
Then you just send messages to that handler as needed.
networkHandler.sendEmptyMessage(1);
Part 2 - Network Thread to UI
There are a couple of different ways to handle this. You can create a handler inside the Activity class. All activities have a Looper already setup, so calling Looper.prepare and Looper.loop seem to cause problems.
In my code I create a handler in the onCreate() method, and then I pass it into my NetworkThread object. There may be better places to create this Handler, I don't know what will happen if your application is suspended and then started again later with onResume() or onRestart()
public NetworkThread(Handler mainHandler)
{
this.mainHandler = mainHandler;
}
Then anywhere else I need to send a message to the UI:
this.mainHandler.sendEmptyMessage(1);
I prefer this method because the Handler code, that does the actual work, either exists in the classes the actually respond to the message (using the anonymous Handler objects) or in Handler subclasses that may be in the same package.
You could also pass in the Activity or a View to the network thread and from that call runOnUIThread(Runnable), but that requires you pass in a Runnable. So the code that is meant to work on the UI is being written or referenced in the Networking classes.
Update
You could also use a Service for this. The method above works when the Activity and the Networking have the same life span. If we only need network connection while the Activity is active.
If you need network connectivity beyond the life of the Activity, in a music streaming app for example, then going with a Service would be a better choice. It didn't seem like this was specifically what you were looking for the question.