Start a new thread from JSP ???

suppose my JSP code is like this,
<%
Obj.heavyProcess();
%>
How can I start a new thread to do
out.println(" ");
out.flush("");
while the heavyProcess is going on? I need to do this because my ISP will cut any Idle connection after certain time and my heavyProcess takes a long time to finish.
for certain reasons, I can not do waiting page, refreshing, etc.

The same way as you would from a normal java application. Write your thread class
package com.yourpkg;
public class YourHeavyProcess implements Runnable{
   private YourObject obj;
   public YourHeavyProcess(YourObject obj){
            this.obj = obj;
   public void run(){
       obj.heavyProcess();
}and create and invoke this thread from your jsp.
<%
        YourObject obj = new YourObject();
        Thread t = new Thread(new YourHeavyProcess(obj));
        t.start();
%>
out.println()..;
out.flush()....;Note that the thread cannot write anything to the output stream as the response is over and done with. It can only perform backend tasks (like data archival for instance)
You could consider using a Timer and a TimerTask class which provides a slightly higher abstraction layer over threads . Look at [url http://forum.java.sun.com/thread.jspa?threadID=758874]this  post (reply 48) for an example.
And finally you wouldnt want a large number of threads to be generated and competing for cpu time on your web server (whose primary responsibility is to receive http requests and send responses). You can use a thread pool to manage the number of threads spawned by your application. If you use java5, take a look at the [url http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/Executors.html]java.util.concurrent.Executor class for thread pool implementations that you can use off the shelf.
cheers,
ram.

Similar Messages

  • Is there a way two start a new thread from a BLS to do some background work

    Hi all-
    I am thinking about creative ways to do offline processing...  Our MII app loads a list of current orders for the user's browser.  The user selects an order and requests back to MII for running the SAP transactions.  Then their browser is reloaded with the up to date list again.  When SAP is down they cannot process.
    Certainly a traditional store and forward where all data is loaded to MII and transaction requests are queued up to be processed by MII/SAP in the background is possible. Con: Data synch issues are very complex however.  Pro: It does provide excellent response time to the user.
    I am just noodling about options... 
    >>Is there a way to start a thread that could take the XML output going to the web page and store that in the database in the background?  I.E.  release the data to the irpt and terminate the user's BLS while a background BLS is saving a copy of the XML/orders to the database.
    Then when offline, the user can work from the last current list of orders they had.  When SAP comes back up the system goes back to online operation.  Thus the data sync would only be temporary.  It does not have the response time benefit however.  Maybe some more thinking, ...But I really want to know if there is a way to multi-thread this app.
    Thanks,
    --Amy Smith
    --Haworth

    I assume you're still running 12.0?  12.1 introduces a new action block for transaction calls, which allows for async threads to nested transaction calls.
    I don't know how using query caching would work on the XacuteQuery template for your list of orders - especially when it would attempt to renew the cache when SAP was unavailable.
    An XML file periodically saved to the web tab of your project would also provide you with a cache approach to servicing the user screen - a simple point of abstraction.

  • Starting new threads from within shutdown hooks

    I'd like to discuss this statement from the java 6 API:
    "A shutdown hook is simply an initialized but unstarted thread. When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. *When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled. Finally, the virtual machine will halt*. Note that daemon threads will continue to run during the shutdown sequence, as will non-daemon threads if shutdown was initiated by invoking the exit method. "
    Now, my question is this: If I have a hook that starts a new non-daemon thread and then goes on to complete it's run() method, will the JVM finalize and halt? Or will it wait for my new thread to complete as well?
    I trust the specification, and believe that the JVM will either not allow me to create the thread or will finalize and shutdown even if it is running. However it's not explicitly stated anywhere, and I think that it's a hole in the documentation.
    I'm going to write a test case for this now. But chime in if you have thoughts.

    This is what happens if you start a new thread from a shutdown hook and do not wait for it to finish:
    public class ShutdownTest {
        private static class Shutdownhook extends Thread{
            public void run() {
                System.out.println("Shutdownhook starting");
                Thread t = new Thread(){
                    public void run(){
                        System.out.println("Thread successfully started");
                        try{ Thread.sleep(5000); }
                        catch(Throwable e){ System.out.println("Throwable from sleep: "+e); }
                        System.out.println("Thread successfully finished");
                t.start();
                //try {t.join();} catch (InterruptedException e) {}
                System.out.println("Shutdownhook completing");
        public static void main(String[] args) {
            Runtime.getRuntime().addShutdownHook(new Shutdownhook());
            System.out.println("Exiting from main()");
            Runtime.getRuntime().exit(0);
    Exiting from main()
    Shutdownhook starting
    Shutdownhook completing
    Thread successfully startedHowever, as you might expect, if you join() or wait for the thread's isAlive() to return false, you will be able to complete the thread.
    I'll leave someone else to figure out if that new thread gets finalized and if finalizers on exit is on, what happens. Mostly because it doesn't matter for my purposes.
    Enjoy

  • Starting new threads from a servlet

    Hi
    I read somewhere that starting new threads from a servlet is not supported in the future releases of J2EE .
    Any one aware of this.
    I have a listener program started as a new thread from the init method of a servlet which is set to load on startup.
    I have to think about another way to do this if this is not suppported in the future releases
    any comments

    Dr clap
    Actually I was getting some warning messages in my websphere server console when I tried to make JDBC connections from the thread I opened in the servlet.
    Everthing works fine but with the warning messages,
    Then someone from IBM answered me in one of the forums quote
    Cause: These messages are being produced due to an
    "unsupported" environment. When application is
    spinning its own threads from an EJB, spinning a
    thread and accessing a database is not supported (per
    the J2EE specification). One exception to this rule is
    if a Servlet is spinning its own threads and accessing
    a database. The J2EE specification is not clear on
    this, so WebSphere Application Server 5.0 must allow
    for it at this time. IBM is working with Sun to
    clarify this in the specification, so eventually (i.e.
    J2EE 1.4) spun threads from a Servlet accessing a
    database outside of a transaction will not be
    supported either.
    Since we don't want to promote the usage of these
    "naked" threads accessing databases, we are producing
    the warning messages. Although they may be filling up
    the logs, we feel that these are necessary to warn the
    user that they are doing something not in-line with
    the intended usage. Customer should consider changing
    their application to comply with the
    J2EE specification.
    """

  • TS2755 My sister and I have/had an iPhone this week she upgraded and went to an android. Now she cannot receive my text. I have put her phone number as a mobile device. Deleted previous iMessages and started a new thread she still cannot receive my text.

    My sister and I have/had an iPhone this week she upgraded and went to an android. Now she cannot receive my text. I have put her phone number as a mobile device. Deleted previous iMessages and started a new thread she still cannot receive my text. Please tell me how this can be resolved

    the fastest way is to call applecare and they can remove her number from iMessage/facetime.

  • Can I use my email and phone number to start a new conversation from iMessage?

    Can I use my email and phone number to start a new conversation from iMessage?

    Can I use my email and phone number to start a new conversation from iMessage?

  • How to call a sequence in a new thread from C++ dll

    Here is what I am trying to do:
    I implemented a dll that monitors network traffic, and it also supports message handlers that can be triggered when a specific message has been received. Essentially the receipt of a message is like an event causing additional code to be executed. What I need to do is have the message handler in the dll call/execute a sequence (either is the same sequence file that originally called the dll, or in a different sequence file). Also I want the sequence to be executed within the same execution object for the purpose of result collection and report generation. I am expecting the dll to have to launch a new thread to call a sequence because of the asynchronous nature of the message received event.
    There are easier ways to achieve the same result, but one of my goals is to make it easy for a test developer to configure a message handler, by having only one step in their sequence to configure the message handler. I want the rest to be transparent to the user.
    I am unsure about how to implement this feature, so I am asking for any examples, ideas, comments before I start trying things out.

    Assuming that I understand your question correctly, it would seem to be the best way to do this would be to pass the Execution object to the DLL (either through a direct pass of the Execution object or passing the sequence context, from which you can get the Execution).  Then simply call Execution.NewThread, specifying the SequenceFile object (accessible from Engine.GetSequenceFileEx) and then passing the Thread object out as an output.  Your sequence file in which your DLL is called could then simply have a Wait step which is configured to wait on that Thread object.  What happens in this case is that the results are collected for that thread (which is being executed asynchronously) and returned as the results for the Wait step.
    Although you are probably not using LabVIEW, I have attached an example of this in LabVIEW that might be helpful just for seeing the flow.
    Thanks,
    Andy McRorie
    NI R&D
    Attachments:
    thread_test.seq ‏32 KB
    testthread.vi ‏19 KB

  • How stopping a version and start a new one from the previous

    Hi,
    May be someone could help me to erase my basics questions on Robosource control.
    We have to manage several versions of our product documentation and It is not clear how it is managed by robosource control. The documentation tells what can do RBSC (and it seems to be what we need) but they do not explain how to do it (prerequisites, ordered steps, etc), and I do not really succeeded. May be I missed the basics.
    All our projects are added to Robosource control 3 from RoboHelp7 Html from a local directory.
    In the database, we inserted them in a directory corresponding to a version V01.r01.
    I would like to stop this version and start a new one V01.02 with the projects which are V01.01. What is the best way to do this:
    Do I just label the directory V01.01 and "Pin" it ?  In that way how can I recover all the projects and files that were labelled and pinned for version V01.01, if I need them later ?
    Copy and rename directory V01.01 into V01.02 to continue the file modifications without modifiying the same project in V01.01?
    My questions are quite similar to Kristen's questions.
    Please can anyone help ! Thanks !

    Then the (App) tabs from that window are lost unless you can restore an older copy of the sessionstore.js file (Time Machine?) that has that lost window.
    *http://kb.mozillazine.org/sessionstore.js

  • Opening a new browser from jsp

    Hello All,
    I have a requirement in which i have to open a new browser when i click on a Submit button.
    In that browser a specific URL should run and then that browser should be closed.
    Does any one have any idea how to open a browser from jsp page?
    Thanks in advance

    You would need to use javascript, in firefox this would opena new tab, in IE it would open a new window. Google for window.open and you should find some examples of how to do this.

  • How do I start a new game from an application I have already loaded

    I Have been playing farmville 2 country escape As is my husband. we have separate games on separate iPads. My son who does not have a Facebook account as he is too young has been playing with it too but just messing about. So now his iPad has picked up my game. How do I start the game over ie reinstall it as a new user without losing my game or at least be able to separate the games on each iPad. I admit I am baffled by the I cloud. I started him a game centre account but the game is linked to my account. I was hoping to override it with a new game but it hasn't worked.
    HELP

    There is no separate forum for Mail: if you ask in the Snow Leopard forum, stating the outline of the problem briefly in the title of a new thread, that will be the best way to proceed.

  • ISA 4.0 filling in the extension with new field from JSP

    Has anyone tried to fill in the extension structure from JSP like the order.jsp?  Using the OSS note, 454715 there seems to be a way to do this.  For outbound, it works with the name, value pair but I am having problem for inbound.  Follwing is the code for order.jsp and the BAdI; this should eliminate the need for creating the backend object, business object and XCM Configurations.
    - Order.jsp
    <%
    //Choi- Reason Code Entry
         (BusinessObjectManager.ISACORE_BOM);
             Basket basket = isaBOM.getBasket();
              String extBasketHeaderData = (String)request.getAttribute("ZCust1");
                  basket.addExtensionData("ZCust_field1", extBasketHeaderData);
    %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
      <head>
    2. BAdI;  CRM_ISA_BASKET_HEAD-changehead_before_order, 
    method if_ex_crm_isa_basket_head~changehead_before_order .
    data: is_it_extension type crmt_isales_extension,
          is_ct_orderadm_h type crmt_orderadm_h_com.
    data ls_cs_basket_head type crmt_isales_baskethead_ui.
    *clear ls_extension.
      loop at it_extension into is_it_extension.
        if is_it_extension-name = 'ZCust_field1'.
         CS_BASKET_HEAD-DESCRIPTION = ls_extension-value.
          append is_ct_orderadm_h to ct_orderadm_h.
        endif.
      endloop.
    endmethod.

    Hi Kyo,
    How did you do it?
    Regards,
    Michael Goossens

  • How to start a new thread and getting mail alerts from the OTN ?

    Hi ,
    I would like to post some question in OTN and at the same time , i am intrest to get the forums mails into my mail box.
    Can you help !!!!!!!!
    Thanks

    IndianDBA wrote:
    I would like to post some question in OTN and at the same time , i am intrest to get the forums mails into my mail box.You could probably help yourself as well.
    There is a FAQ link at the upper-right of the page - FAQ stands for 'Frequently Asked Questions' and usually provides answers to those questions. ANd your questions just may be answered there if you care to look.
    I note that not only 'would you like to post some questions', but you actually 'have posted the first question'. So you seem to be on your way. Just note that there are many forums, and you are encouraged to ask in the correct forum - find them by going to the 'Forum Home' link (top left) and scrolling down (and don't forget to peek in the 'More...' areas if you can not find the ones you want.)
    AND - if you ask technical questions, remember to include operating system (including edition or distribution and version as appropriate for the OS), product version (even if you do not think it's important) and any error messages (copied, not re-typed, if possible)

  • ITunes 11 Stops Responding to Bonjour Discovery Multicast Broadcasts, Why?  This stops the the Apple TV 3 from being able to start a new stream from the home share and the iPad remote app can no longer see the home share too.

    I'm having an issue where my Apple TV 3 and all our iPads periodically seem to loose connectivity to an iTunes home share on a Windows 7 PC.  Using a network protocol analyser on the PC I have identified that the point of failure corresponds to the ATV3 sending a bonjour discovery request and getting no reply from iTunes.  Why the ATV3 'forgets' where the home share is is possibly another issue but the root cause of the failure is that iTunes, or more specifically the mDNSResponder service, is not responding to the UDP multicast port 5353 broadcast discovery packet sent by the ATV3 or iPad.  The mDNSResponder service does start responding again after iTunes is restarted thus making the home share accessible once more, however, this frequent drop out is unacceptable and often happens after only a single TV show has been watched from the home share making the solution unworkable for a family, we simply cannot be restarting iTunes constantly it ruins the user experience completely!
    The nature of this failure indicates that the ATV3, the iPads, the host PC and network are all working correctly and the point of failure here is the lack of response to the bonjour discovery protocol with the net result of either a spinning 'connecting to home share' message or the home share just disappearing from the computers section.
    If there is a configuration fix for this please let me know as I haven't located a fix!  Otherwise this seems very much to be a code flaw in iTunes 11 or the mDNSResponder and I would appreciate some input from Apple!  Going on other questions in these forums it would seem the problem is not limited to Windows PCs but also Macs too.  NB: This is not a TCP issue, when the ATV3 or iPad knows the IP of the iTunes server all works flawlessly, it just periodically they seem to refresh the list of home shares and at this point they loose the information about the home share they have just been using because of the non-response to the UDP multicast discovery broadcast packet, that is arriving at the host PC and isn't being blocked by the firewall.
    Many Thanks!

    In my case there was no import from a former mac.
    My problem (at least mine) is that no app that offers media sharing works properly. Neither itunes home sharing nor AirVideo nor EyeTV sharing.
    So I'm pretty sure that this is network issue.
    Adding another user on my mac and sharing a new library works not also. But sharing from another laptop in my WiFi works. So this has to be a network issue on my mac, not only my user, but an issue of the whole system.
    But I'm not willing to reinstall MacOS X for that if I don't have to.

  • Start a new process from a running process BPM 10.3 STUDIO!

    Is it possible to create a process in BPM Studio 10.3 from a running process.
    The scenario is that we have a process running listening to a jms queue an when a message
    arrives it's starts the process that was requested in the in message.
    /Getr

    if you have a Global Automatic activity listening to a JMS queue, here's how you can create a new work item instance in a process using logic in the Global Automatic activity's method. This uses the "Fuego.Lib.ProcessInstance.create()" method shown below:
    // "args" is an associative string array (Any[String])
    argsIn as Any[String]
    // this assumes that the Begin activity has two argument variables
    //   named "nameArg" and "amountArg" and you're setting them
    //   to the variables "name" and "amount" respectively
    argsIn["someArgVarName"] = "Hello"
    argsIn["someBpmObject"] = myBpmObject
    // logic here to determine the name of the process to create an instance in
    idOfProcess as String
    idOfProcess = <hard coded string that has the id (not the name of the process to instantiate>
    ProcessInstance.create(processId : "/" + idOfProcess, arguments : argsIn, argumentsSetName : "BeginIn") ProcessInstance is in the Catalog inside Fuego.Lib.
    The processId parameter (the "idOfProcess" variable in the above logic) is the thing I most commonly screw up with this. It is the text you see when you right mouse click the process in the Project Navigator tab -> "Properties". Look at the value in the "Id" field and not the "Name" field here (the name without any space characters). Prefix it with a "/" as is shown here and if you've deployed this using an organization unit (OU) then prefix this to the string also.
    The third parameter is almost always "BeginIn". Begin activities in a process can have many incoming argument mappings, the default is "BeginIn". To see yours, double click the process's Begin activity and look at the mapping's name in the upper left corner of the dialog.
    "argsIn" is the set of incoming argument variables you want passed into the process. A common mistake is to type in the names of the incoming argument variables without the double quotes like this:
    // this will *NOT* work
    argsIn[someArgVarName] = "Hello"
    argsIn[someBpmObject] = myBpmObject
    . . .Here is the correct syntax:
    // this *WILL* work
    argsIn["someArgVarName"] = "Hello"
    argsIn["someBpmObject"] = myBpmObject
    . . .In this example, the process has two argument variables. It does not matter if the incoming argument variables are primitive type arguments (e.g. String, Integer, Decimal...) or BPM Objects, it is always done the same way. In this example, there is a String incoming argument called "someArgVarName" and a BPM Object incoming argument called "someBpmObject".
    Dan

  • In dreamweaver 5 I want to start a new site from scratch, where do I start?

    What is the first thing I should do to start my webpage in DW5?

    Here is a 6-part tutorial series for building a website in CS5: Creating your first website – Part 1: Set up your site and project files | Adobe Developer Connection
    Hope that helps!

Maybe you are looking for

  • Error in replicate created BP in CRM 7.0 to ERP

    Hi you all. When I create a new BP in CRM, and go to SMW01 the BDOC gives un error, the message is that I didn't fill all required fields. I've check and the account group that should recieve the BP in ERP don't have in obrigatory fields. The strange

  • TA20637 I have a print job that I can not delete from the queue.

    When I try it says "job is completed and can not be deleted from queue" but it seems to be stuck (and keeps reprinting rather than letting me print other documents). What do I do?  I tried clearling the printer queue by turning the printer on and off

  • Change of apple ID details for updating

    When I initially setup my PC I registered it with an apple account which it prompts for when wanting to update software and also apps, I would now like to change this to use a different account. How do I go about it?

  • Portal exception monitoring

    Hi everyone, we seem to have a problem every now and again with our portal (EP6 sp15) which causes exceptions written in the logs and iViews not being displayed. We believe it has something to with the communication to the backend system but the logs

  • Updating a Deployed J2EE Application Component

    Hi All, I was going through this link below : http://e-docs.bea.com/wls/docs61/adminguide/utils.html#1139180 Updating a Deployed J2EE Application To update a specific component, enter the following commands: % java weblogic.deploy -port 7001 -host lo