This Q is asking for resources/direction rather than a specific answer. we're looking to understand the Vaadin architecture on the following problem.
Our application is event-driven, event here being a server-side event.
When our application hears from another, independent application on the server, it asks the front-end (human) user
to fill out a form, waits till the user does, and proceeds based on what the user said.
Our backend process, say processB is calling a method on a Vaadin layout to do the deeds. that method, say methodA() is
supposed to
push the form to front-end
wait till the user enters data and hits the "OK" button
process&return what the user entered.
(1) is working fine. however, the method is returning before the front-end form is processed. This and some other stuff we observed here suggest that Vaadin is running
two different threads for methodA(). So, when we invoke
ourUI.methodA();
2 different threads are initiated and running to execute it.
Can this be true?? What is the Vaadin logic on this?
it isn't a thread from a previous run of the application still remained on the server-- i checked that carefully
What's the best way to make a process wait for a Vaadin event? is there a way to make an independent thread, i.e., a thread that is outside the control of Vaadin UI, wait for a Vaadin event?
we can make processB join methodA() so that it'll wait until methodA() returns. but I don't think this is the best way. and i don't know how to get hold of a Vaadin thread to join() it. furthermore, those (seemingly) 2 methodA() threads are spoiling it.
we can keep a token for what methodA() returns and make processB keep an eye on it, wait till value is written there. still-- there must be a better way.
We'll merge processB into Vaadin UI (early days yet in development) so that it'll keep running until the UI is terminated. It no longer will be outside the ourUI. How does this simplify things?
Note: we've got only one UI for one session/user-- not allowing multiple tabs by specs, and one backend process on one UI/user
We're using Vaadin 7.7 on Java 1.7 and Tomcat 8
//-------------------------
EDIT:
Our backend process, processB is a Runnable itself and controls the whole logic. it has to wait for the front-end thread return and deliver the value. what i'm looking for is how to trigger this-- getting the value when front-end event returns. processB won't proceed until it gets this value from the front-end.
Related
I am trying to build something, which requires multithreading functionality. The desired work was not done using javascript i.e. Web-Workers.
So I changed focus from javascript to JSP. Now I want to call one method which will execute series of some queries, and at the same time I want to show the affected table rows on other hand. And when first process done with it's execution, I want to stop other process also. My work is done but statically. Now I want to share some resource between this two threads. So that when first thread done with it's execution, I will set some value to that resource(variable,flag), and check that resource in another thread. Is it possible to access variable of one thread in another while it running.
Thanks
JavaScript in a browser is per design not capable of multithreading. You can simulate it a little bit when using setTimeout or setInterval methods.
But, as with the introduction of HTML5, there are now so called WebWorkers available. They run completely separate, spawn a real OS thread, do not have access the DOM but can interact with your UI application e.g. via events.
I have a GUI and the GUI is starting another thread (Java). This thread is starting a class which is crawling many websites. Now I want to show in the GUI how many websites are crawled and how many are left.
I wonder what's the best solution for that.
First idea was to start a timer in the GUI and periodically ask the crawler how many is left. But I guess this is quite dirty...
Then one could pass the GUI to the crawler and it is calling a GUI method every time the count of ready websites changes. But I don't think that's much better?
What is the best way to do something like that?
It depends.
Ask the crawler how much work it is done isn't a bad idea. The benefit is you can actually control when an update occurs and can balance out the load.
The downside is that the information may go stale very quickly and you may never get accurate results, as by the time you've read the values, the crawler may have already changed them.
You could have the crawler provide a call back interface, which the GUI registers to and when the crawler updates it's states, calls back to the GUI.
The problem here is the UI may become swamped with results, causing to lag as it tries to keep up. Equally, while the crawler is firing these notifications, it isn't doing it's work...
(Assuming Swing)
In either case, you need to make sure that any ideas you make to the UI are made from within the Event Dispatching Thread. This means if you use the callback method, the updates coming back will come from the crawlers thread context. You will need to resync these with the EDT.
In this case you could simply use a SwingWorker which provides mechanisms for syncing updates back to the EDT for you.
Check out Concurrency in Swing for more details
register a callback function to your thread. when your data is dirty, invoke this callback function to notify GUI thread to update. don't forget to use synchronization.
My Grails 1.3.7 app needs to process big XML files, so I have a controller to which I upload the big file, and then I give the path of this file on the server to a background thread that does the processing so that I can return right away from the controller action.
For now, I am using the Grails Executor plugin and it works fine. I have an Upload domain object that is updated as the processing progresses (current status, number of processed elements, etc.). But now I have 2 more requirements:
when the application crashes or the server is shutdown, I would like to intercept that and update my Upload domain to say that the process was interrupted
I want the user to be able to interrupt the processing himself when clicking a link and possibly resume it from controller actions
Is there a way that I can persist a reference to my background task and intercept any interruption with java.util.concurrent framework (which is used by Executor plugin)?
And if I can't do it with util.concurrent, is it possible with other plugins/frameworks? I've had a look at Quartz for example, but I don't see how to do it.
I hate to answer without fully testing it, but the grails-executor plugin docs state that the callAsync method returns a java.util.concurrent.Future object.
This object can be used to do two things:
Determine if a process has completed or been canceled.
Cancel a running process (even interrupting if necessary).
In theory, you should be able to save this Future in your user's session somewhere. Then you could retrieve it later and use it to check the status and/or cancel the process as necessary.
Something like:
session.backgroundProcess = callAsync{...}
// later
def bgProc = session.backgroundProcess
if(bgProc && !(bgProc.done || bgProc.cancelled)) {
// process is still running
}
That's just the idea, it's not tested. I also don't know if there are issues with this leading to memory leaks. You'd need to make sure you detached the Future once the process is completed.
I have a Java application that downloads information (Entities) from our server. I use a Download thread to download the data.
The flow of the download process is as follows:
Log in - The user entity is downloaded
Based on the User Entity, download a 'Community' entities List and Display in drop down
Based on Community drop down selection, Download and show 'Org Tree' in a JTree
Based on Node selection, download Category entities and display in drop down
Based on Category selection, download Sub Category entities and display in drop down
Based on Sub Category selection download a large data set and save it
The download occurs in a thread so the GUI does not 'freeze'. It also allows me to update a Progress Bar.
I need help with managing this process. The main problem is when I download entity data I have to find a way to wait for the thread to finish before attempting to get the entity and move to the next step in the app flow.
So far I have used a modal dialog to control flow. I start the thread, pop up a modal and then dispose of the modal when the thread is finished. The modal/thread are Observer/Observable the thread does a set changed when it is finished and the dialog disposes. Displaying a modal effectively stops the flow of the application so it can wait for the download to finish.
I also tried just moving all the work flow to Observers. All relevant GUI in the process are Observers. Each update method waits for the download to finish and then calls the next piece of GUI which does its own downloading.
So far I found these two methods produce code that is hard to follow. I would like to 'centralize' this work flow so other developers are not pulling out their hair when they try to follow it.
My Question is: Do you have any suggestions/examples where a work flow such as this can be managed in a way that produces code that is easy to follow?
I know 'easy' is a relative term and I know my both my options already work but I would like to get some ideas from other coders while I still have time to change it.
Thank you very much.
You might want to look into using the Future interface.
Stop by http://download.oracle.com/javase/6/docs/api/java/util/concurrent/package-summary.html
It has all you might need to make these tasks easier.
I think the most common method to do this in recent versions of Java is to use SwingWorker:
http://download.oracle.com/javase/6/docs/api/javax/swing/SwingWorker.html
It allows you to fire off background tasks and gives you a convenient done() method that executes on the Swing EDT.
You have to create a "model" for your view, representing the current state of your application. For a tree e.g. it is reasonable to show a "Loading"-node when someone openes a treenode, because else the GUI hangs on opening a node.
If the loading thread finishes loading the node, the "Loading"-node is replaced with the results of the asynchronous action. This makes it easy to open multiple nodes in parallel, because the worker threads all are just responsible for a single child node.
Similar when downloading something: The workers then update a download progress. The downloads-Dialog of Firefox comes to mind here.
Good GUIs aren't easy :).
Can someone tell me the TRUE difference?
My rule of thumb is that an AsyncTask is for when I want to do something tied to single Activity and a Service is for when I want to do something that will carry on after the Activity which started it is in the background.
So if I want to do a small bit of background processing in the Activity without tying up the UI I'll use an AsyncTask. I'll then use the default Handler from that Activity to pass messages back to ensure updates happen on the main thread. Processing the updates on the main thread has two benefits: UI updates happen correctly and you don't have to worry so much about synchronisation problems.
If for example, I wanted to do a download which might take a while I'd use a Service. So if I went to another Activity in my application or another application entirely my Service could keep running and keep downloading the file so it would be ready when I returned to my application. In this case I'd probably use a Status Bar Notification once the download was complete, so the user could choose to return to my application whenever was convenient for them.
What you'll find if you use an AsyncTask for a long-running process it may continue after you've navigated away from the Activity but:
If the Activity is in the background when your processing is complete you may have problems when you try to update the UI with the results etc.
A background Activity is far more likely to be killed by Android when it needs memory than a Service.
Use Service when you've got something that has to be running in the background for extended periods of time. It's not bound to any activity. The canonical example is a music player.
AsyncTask is great when some stuff has to be done in background while in the current activity. E.g. downloading, searching for text inside a file, etc.
Personally I use Handlers only to post changes to the UI thread. E.g. you do some computations in a background thread and post the result via handler.
The bottom line: in most cases, AsyncTask is what you need.
To complement the other answers here regarding the distinction between service and AsyncTask, it is also worth noting[0]:
A Service is not a separate process. The Service object itself does not imply it is running in its own process; unless otherwise specified, it runs in the same process as the application it is part of.
A Service is not a thread. It is not a means itself to do work off of the main thread (to avoid Application Not Responding errors).
Services tend to be things that describes a significant part of your application - rather than an AsyncTask which is typically contributes to an Activity and/or improves UI responsiveness. As well as improving code clarity Services can also be shared with other applications, providing clear interfaces between your app and the outside world.
Rather than a book I would say the developer guide has lots of good answers.
[0] Source: http://developer.android.com/reference/android/app/Service.html#WhatIsAService
AsyncTask: When I wish to do something without hanging the UI & reflect the changes in the UI.
E.g.: Downloading something on Button Click, remaining in the same activity & showing progress bar/seekbar to update the percentage downloaded. If the Activity enters the background, there are chances of conflict.
Service: When I wish to do something in the background that doesn’t need to update the UI, use a Service. It doesn’t care whether the Application is in the foreground or background.
E.g.: When any app downloaded from Android Market shows notification in the Status Bar & the UI returns to the previous page & lets you do other things.
Service
A Service is an application component that can perform long-running operations in the background and does not provide a user interface. Another application component can start a service and it will continue to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with.
When to use?
Task with no UI, but shouldn’t be too long. Use threads within service for long tasks.
Long task in general.
Trigger: Call to method onStartService()
Triggered from: Any Thread
Runs on: Main thread of its hosting process. The service does not create its own thread and does not run in a separate process (unless you specify otherwise)
Limitations / Drawbacks: May block main thread
AsyncTask
AsyncTask enables the proper and easy use of the UI thread. This class allows performing background operations and publishing results on the UI thread without having to manipulate threads and/or handlers. An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread.
When to use?
Small task having to communicate with main thread
For tasks in parallel use multiple instances OR Executor
Disk-bound tasks that might take more than a few milliseconds
Trigger: Call to method execute()
Triggered from: Main Thread
Runs on: Worker thread. However, Main thread methods may be invoked in between to publish progress.
Limitations / Drawbacks:
One instance can only be executed once (hence cannot run in a loop)
Must be created and executed from the Main thread
Ref Link