How to make a Thread pause in Spring mvc project? - multithreading

I am using a Thread in Spring mvc project to do some background working.
What I have done is
I write a class which extends Thread. and I added init() method to start this class.
Whole ThreadTest.java is Below.
package org.owls.thread.vo;
public class ThreadTest extends Thread {
public void init(){
this.start();
}
public void pause(){
this.interrupt();
}
#Override
public void run() {
for(int i = 0; i < 100; i++){
try{
Thread.sleep(3000);
System.out.println("Thread is running : " + i);
} catch(Exception e){e.printStackTrace();}
}
}
};
edit root-context.xml intent to start this Thread as soon as possible when the server started.
<bean id="threadTest" class="org.owls.thread.vo.ThreadTest" init-method="init"/>
Now is the problem. I want to make a toggle button(pause/resume) in my home.jsp and When I click the button it works. But I do not know how can I access to the Thread, which already registered and run.
please, show me the way~>0<
P.S
additional question about java Thread.
What method exactly means pause and resume. I thought stop is the one similar to pause, but it is deprecated.
And start() is somehow feels like 'new()' not resume.
Thanks

I figured out how to control a thread.
if I want to pause(not stop), code should be like below.
thread.suspend();
And want to resume this from where it paused, like below.
thread.resume();
even though those methods are both deprecated.
(if somebody knows some replacement of these, reply please)
If you do not want to yellow warning in your spring project,
you can remove warning by simply add an annotation on that method.
annotation is #SuppressWarnings("deprecated").
=========================================================
From here, additional solutions based on my experience.
To make automatic executing Spring mvc Thread,
I did following steps.
make a simple Class which extends Thread class.
inside that class, make a method. this will be calles by
config files. in this method. I wrote code like "this.start();".
Let Spring knows we have a Thread class that should run independently
with Web activities. To do this, we have to edit root-context.xml.
Add a bean like this.
<bean id="threadTest" class="org.owls.thread.vo.ThreadTest" init-method="init"/>
init is the method name which generated by user in step 2.
Now we run this project Automatically Thread runs.
Controlling Thread is not relavent with Spring, I guess.
It is basically belongs to java rules.
I hope this TIP(?) will be helpful to people who just entered world of programming :-)

Related

Using Camel Processor as custom component

I want to make a custom camel processor to behave as a custom component.I read it as it as possible from http://camel.apache.org/processor.html - section--> Turning your processor into a full component.
Here the Custom Processor created will have to do the job when i call
someComponent://action1?param1=value1&param2=value2
in the route.
For this i created a sample component using maven catalog.This created Endpoint,Consumer, Producer and Component classes.
The link says that the component should return ProcessorEndpoint which i have done.
So, Endpoint looks as below
public class SampleEndpoint extends ProcessorEndpoint{
// Automatically Generated code begins
public Producer createProducer() throws Exception{
return new SampleProducer(this, processor);
}
public Consumer createConsumer() throws Exception{
throw new UnsupportedOperationException("This operation is not permitted....");
}
// Automatically generated code ends here
//added below to make custom processor work for custom component
public Processor createProcessor(Processor processor){
return new SampleProcessor();
}
}
But, here the code in the processor is not getting executed instead the code in the SampleProducer gets executed.
Here i want the processor to be excuted.How do i do that?
When extending ProcessorEndpoint, the Producer from createProducer() will handle the exchange, i.e. Producer.process(Exchange exchange).
This is why you are seeing SampleProducer being used. But if you wanted to delegate to a processor, you could probably just change your code to be:
return new SampleProducer(this, new SampleProcessor());
My best advice would be to attach a debugger and put breakpoints in your SampleEndpoint, SampleProducer and SampleProcessor methods to see what gets called and when.

Accessing WinForm UI from Rhino Service Bus consumer [duplicate]

This question already has answers here:
Invoke or BeginInvoke cannot be called on a control until the window handle has been created
(8 answers)
Closed 9 years ago.
I have a WinForm screen that is also a message consumer (using Rhino ESB). If I try to update anything on the screen when I receive a message, nothing happens. A call to Invoke gives me an error that the handle is not created. The form is definitely created though, I'm firing a message on button click on the form and the background process sends a message back. It's with this return message I want to update the UI.
THIS IS NOT A DUPLICATE QUESTION, NONE OF THE SUGGESTED SOLUTIONS WORK.
I believe the difference here may be because I'm using Rhino Service bus. Rhino may be constructing a separate instance of my form rather than the one I'm using. I think what I probably need to do is to have Rhino use my instance of the form as the consumer by passing my instance into the IoC container Rhino is using. Another alternative is to move the Consumer off to it's own class and inject my Form into the consumer, and put a public method on my Form for the Consumer to use. This may work fine with my app because this is the main form and will never be disposed unless the app is closed. This would become problematic on another form that may be instantiated multiple times. Perhaps I could have my form "observe" another static object that a separate Consumer class updates. Please give suggestions as to the best approach.
public partial class MainForm : Form, ConsumerOf<MoveJobCompletedEvent>
{
public void Consume(MoveJobCompletedEvent message)
{
// This does nothing!
txtLogs.Text = "\nJob completed!";
}
}
This throws an error:
this.BeginInvoke((MethodInvoker)delegate
{
txtLogs.Text += "\nJob job completed!";
});
ERROR: Invoke or BeginInvoke cannot be called on a control until the window handle has been created.
It seems that you're consuming a JobCompleted event before the window handle is created. You could try the following:
public partial class MainForm : Form, ConsumerOf<MoveJobCompletedEvent>
{
public void Consume(MoveJobCompletedEvent message)
{
if (!this.HandleCreated)
return;
this.BeginInvoke((MethodInvoker)delegate
{
txtLogs.Text += "\nJob job completed!";
});
}
}

Java Thread Safety v Displaying a Dialog from separate Thread

Hi noticed some code in our application when I first started Java programming. I had noticed it created a dialog from a separate thread, but never batted an eye lid as it 'seemed to work'. I then wrapped this method up through my code to display dialogs.
This is as follows:
public class DialogModalVisibleThread
extends Thread {
private JDialog jDialog;
public DialogModalVisibleThread(JDialog dialog, String dialogName) {
this.setName("Set " + dialogName + " Visable");
jDialog = dialog;
}
#Override
public void run() {
jDialog.setVisible(true);
jDialog.requestFocus();
}
}
Usage:
WarnUserDifferenceDialog dialog = new WarnUserDifferenceDialog( _tableDifferenceCache.size() );
DialogModalVisibleThread dmvt = new DialogModalVisibleThread( dialog, "Warn User About Report Diffs");
dmvt.start();
Now, as far as I am now aware, you should never create or modify swing components from a separate thread. All updates must be carried out on the Event Dispatch Thread. Surely this applies to the above code?
EDT on WikiPedia
However, the above code has worked.
But lately, there have been countless repaint issues. For example, click on a JButton which then calls DialogModalVisibleThread to display a dialog. It caused buttons alongside the clicked button not to redraw properly.
The repaint problem is more frequent on my machine and not the other developers machine. The other developer has a laptop with his desktop extended onto a 21" monitor - the monitor being his main display. He is running Windows 7 with Java version 1.6.0_27.
I am running on a laptop with Windows 7 and Java version 1.6.0_24. I have 2 additional monitors with my desktop extended onto both.
In the meantime I am going to upgrade to Java 1.6 update 27.
I wondered if the above code could cause repaint problems or are there any other people out there with related paint issues?
Are there any easy ways to diagnose these problems?
Thanks
So, you're breaking a rule, having problems, and wondering if these problems could be cause by the fact that you broke the rule. The answer is Yes. Respect the rules!
To detect the violations, you might be interested by the following page: http://weblogs.java.net/blog/2006/02/16/debugging-swing-final-summary
The easiest way to check if your problems are being caused by breaking the rules is to fix them (You should fix them anyway :-)
Just use SwingWorker.invokeLater() from the thread you want to update to UI from to easily adhere to Swing's contract. Something like this should do the trick:
#Override
public void run() {
SwingUtilities.invokeLater(new Runnable() {
jDialog.setVisible(true);
jDialog.requestFocus();
}
});
}
EDIT: You should make the 'jDialog' variable final for this to work.

Multiple Threads in Xpages

I have a problem and hoped somone could help me
I'm trying to start multiple threads from an XAgent (not rendered XPage)
public class ImportThread extends NotesThread {
Session currentSession;
public ImportThread(String maildb, String Server)
{
try{
currentSession =DominoAccess.getCurrentSession();
this.maildb = currentSession.getDatabase(Server, maildb);
}catch (Exception e) {
e.printStackTrace();
}
}
public void runNotes()
{
View v = maildb.getView("$Calendar");
}
in this version I could not access the View I only get "null" back
Ive tryed a version with Java Threads not realy better.
thean i've found something on Openntf
http://www.openntf.org/internal/home.nsf/project.xsp?action=openDocument&name=Threads%20and%20Jobs
but there I got an "AccessControl Exception"
I have no more ideas, I hope that someone has an idea how to create
an XAgent with multiple thread
As Egor wrote you need the change the Java policy file if you run the Java code from an NSF. You don't have to do this if you deploy your Java code as OSGi plugin. See the documentation of that OpenNTF project.
Afaik NotesObjects should not be shared between threads. So instead of using Database mailDB you should use String mailDBName and instantiate all NotesObjects inside their own thread. You also need to watch run time: if your XAgent waits for the treads to conclude, you should be fine, but if it is a 'fire-and-forget' approach you need to start it from something more persistent like a managed bean in the session scope.
Hope that helps

Handling threading and web requests on Windows Phone 7

How can you make a background web request and then update the UI, but have all the code that does the web requesting/parsing in a separate class so you can use it in multiple places? I thought I could use the classes methods as event handlers for a BackgroundWorker class, like
APIHelper mHelper = new APIHelper("http://example.com?foo=bar");
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork +=new DoWorkEventHandler(mHelper.GetResponse);
bw.RunWorkerCompleted +=new RunWorkerCompletedEventHandler(mHelper.HandleResponse);
bw.RunWorkerAsync();
where APIHelper has the method
public void GetResponse(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = (BackgroundWorker) sender;
WebRequest request = HttpWebRequest.Create(this.URL);
IAsyncResult result = (IAsyncResult)
request.BeginGetResponse(ResponseCallback, request);
}
but then I don't know how to access the worker thread from ResponseCallback and, anyway, HandleResponse gets called first (obviously). (I tried putting in result.AsyncWaitHandle.WaitOne(); but I get a NotSupportedException error.) Yet I can't work out how to make the web request call synchronously. I'm clearly trying to go about this the wrong way, but I have no idea what the right way is.
ETA:
My aim is to be able to go:
user clicks (a) button(s) (on various pages)
a "working" message is displayed on the UI thread (and then input is blocked)
in a background thread my APIHelper class makes the relevant API call, gets the response, and passes it back to the UI thread; I only seem to be able to do this by starting another thread and waiting for that to return, because there's no synchronous web requests
the UI thread updates with the returned message (and input continues as before)
I can do the first two bits, and if I have the response, I can do the last bits, but I can't work out how to do the middle bit. Hopefully that made it clearer!
It took me several tried before I found there is a Dispatcher.
During the BackgroundWorker's dowork and complete methods you can call:
this.Dispatcher.BeginInvoke(() =>
{
// UPDATE UI BITS
});
I think the Dispatcher is only available in the view. So I'm not sure if the methods can exist outside of the xaml.cs
Put whatever you want to update in your UI; when updating an ObservableCollection you must do the update of you items in the Dispatcher.BeginInvoke too
This link might be a good read too:
http://www.windowsphonegeek.com/articles/All-about-Splash-Screens-in-WP7-ndash-Creating-animated-Splash-Screen
Update to assist notes
This is just a rough idea mind you...
bw.DoWork +=new DoWorkEventHandler(DoWork);
bw.RunWorkerCompleted +=new RunWorkerCompletedEventHandler(Complete)
// At least I think the EA is DoWork....
public void DoWork(object sender, DoWorkEventArgs e)
{
mHelper.GetResponse();
this.Dispatcher.BeginInvoke(() =>
{
UIObject.Visibility Collapse.
});
// Wait and do work with response.
});
}
public void Complete(object sender, RunWorkerCompleteEventArgs e)
{
this.Dispatcher.BeginInvoke(() =>
{
UIObject.Visible ....
});
}
I'd put all this logic in a viewmodel that the viewmodel of each page inherits from.
Have the pages bind to properties on the viewmodel (such as ShowLoading, etc.) which the model updates appropriately. i.e. before making the webrequest and in the callback.
As you won't be running the viewmodel code in the UI thread you also wouldn't need to run in a separate BackgroundWorker and you'll be able to access the properties of the viewmodel without issue.
It might be useful if you use a helper class that I have developed for WebDownload purposes during WP7 development.
I'm using it in 2-3 WP7 apps and no problem so far. Give it a go to see if it helps. You can get the class from the my blog linked bellow:
http://www.manorey.net/mohblog/?p=17#content
[NOTE] When working with this class you don't need to run anything in a background worker or new thread; it handles it all asynchronously.

Resources