Trouble rationalizing use of multi-threading in run of the mill servlets

Hey everybody,
While spending time writing an internal wiki article on servlets for work, I asked myself a very basic question: What does multi-threading buy average servlets where the business logic requires procedural handling of the request?
Don't get me wrong: I appreciate the fact that servlet containers spawning a new thread being less expensive than spawning an entirely new process is helpful and efficient. Coming from a background in PHP, it is great how servlets maintain persistence. However, as more of my coworkers are required to gain proficiency in Java and designing servlets, it is a question that many will ask and aside from having real-time processing of data files and other arduous tasks, I cannot think of any instances of where multi-threading benefits the application.
What are some of the ways that you are using multi-threading with web applications?
How would you explain why and where you would want to use multi-threading to someone?
Thank you in advance for your insight,
Andy

how can we pass arguments to the run ()method?Create classes which implement Runnable that take your runtime parameters as constructor arguments and store them.
eg: if your single thread method is   static void foo (int quantity, String name) {
    for (int i=0; i<quantity; i++) {
      System.out.println(name);
// caller code
  foo(7, "wombats");Then you can make a runnable implementation thus:public class Foo implements Runnable {
  final int quantity_;
  final String name_;
  public Foo (int quantity, String name) {
    quantity_ = quantity;
    name_ = name;
  public void run () {
    for (int i=0; i<quantity_; i++) {
      System.out.println(name_);
// caller code
  new Thread(new Foo(7, "wombats")).start();
You could overload this method to take parameters in
your class that implements the Runnable interface,
and then call the base run() method.I don't get what you mean by this; Runnable is an interface so there is no base class run() method, and a run() overloaded with extra parameters method wouldn't get called by the thread.
Pete

Similar Messages

  • Multi-threads will run better on multi-Processores environment?

    Are there any proof to say that Multi-threads will run better on multi-Processores environment?
    Will Java run better on multi-Processores environment? Are there any proof?
    Thank in advance

    Are there any proof?The proof is in the pudding, so to speak. The best thing to do is to benchmark your application on single and multi-processor machines.
    It should be noted that there are reports of threading problems with Java on multi-processor machines. I haven't seen the problems myself, nor do I remember the exact problems people were seeing (and on what OS/Hardware) but if you search these forums you should be able to find out the details.

  • If I come out of my house using wifi, but fb is running in the background, will it start to use up my data for 3G?!

    If I come out of my house using wifi, but fb is running in the background, will it start to use up my data for 3G?!

    Unless you are actively accessing the FaceBook app or actively accessing FaceBook via Safari, nothing is being downloaded.
    This applies to iOS 5 as well.
    http://whenwillapple.com/blog/2010/04/19/iphone-os-4-multitasking-explained-agai n/

  • Is the directory watcher multi-threaded once it calls the cfc?

    the docs say there's a single thread that watches the directory.  But say for example it finds 3 files and calls the cfc.  At that point do all 3 files run one at a time on a single thread in the order they came in, or do they run at the same time on multi-threads?

    I think I understood your questions. There were more than one, some implicit. Here are my answers:
    ColdFusion runs the directory-watcher in a single thread.
    During the execution of the same thread, ColdFusion detects whether of not a file has, or any number of files have, been added, deleted or changed.
    When ColdFusion calls the CFC, it does so in that same single thread. My guess is that any file add-events, delete-events and change-events are queued and handled one after the other.

  • When I click on a new link, it opens a whole new firefox instead of using my default which is running in the background

    I have firefox as my default browser. Anytime I click on an email or search for something, instead of opening my default browser, firefox loads a new firefox page. It is a blank page just as if I had never had one. It has nothing on it except how you would start out before you set up your tabs and history etc. My default firefox is still there running in the background but I must click on it and manually put in the link I was trying to open.
    Any suggestions.

    Some added toolbar and anti-virus add-ons are known to cause
    Firefox issues. '''Disable All of them.'''
    Start '''[https://support.mozilla.org/en-US/kb/troubleshoot-firefox-issues-using-safe-mode Firefox in Safe Mode]''' {web Link} by holding down the '''<Shift ''(Mac Options)'' >''' key, and then starting Firefox. Is the problem still there?

  • Can't get my threads to run at the same time  :-(

    Hi,
    I hope someone can help me. I have an two instances of an object that extends thread. In it's run method, there is a while loop that iterates while an int x (that starts at about 450) is not less than 0.
    In the while loop there is an x--; statement.
    Also inside the while loop is a call to yield();
    Also is a call sleep(5);
    Also in the while loop is a statement something like "System.out.println(x);"
    The int controls the vertical position of an icon (a JLabel) on the screen.
    In the class that has the main method, two instances of the thread object are created one after the other and run one after the other, although the program keeps running the first one until it has finished before running the second one!
    For example, the code looks something like this:-
    o1.run();
    System.out.println("o1 running");
    o2.run();
    System.out.println("o2 running");
    And the end printout (with the println call from the thread objects) looks like this:-
    o1 running
    450
    449
    448
    3
    2
    1
    o2 running
    450
    449
    etc.
    What's going on? Why won't it start running the second thread straight after the first one?
    Any help appreciated!

    class test extends Thread {
      private int i = 0;
      private String strMess = new String("");
      public static void main (String[] args)  {
         test t = new test("first");
         t = new test("second");
      test(String strIn){
           this.strMess = strIn;
           this.start();
      public void run(){
           while(i<5){
              System.out.println(this.strMess + i);
              try{this.sleep(200);}catch(Exception e){e.printStackTrace();}
              i++;
    }output:
    first0
    second0
    first1
    second1
    first2
    second2
    first3
    second3
    first4
    second4
    class test extends Thread {
      private int i = 0;
      private String strMess = new String("");
      public static void main (String[] args)  {
         test t = new test("first");
         t = new test("second");
      test(String strIn){
           this.strMess = strIn;
           this.run();
      public void run(){
           while(i<5){
              System.out.println(this.strMess + i);
              try{this.sleep(200);}catch(Exception e){e.printStackTrace();}
              i++;
    }output:
    first0
    first1
    first2
    first3
    first4
    second0
    second1
    second2
    second3
    second4

  • StringBuffer when used with multi thread show output in UnSynchronize way.

    below is my code :-
    public class Two implements Runnable
         //thread safe
    static StringBuffer builder=new StringBuffer("output:1");
    Two(StringBuffer builder)
              this.builder=builder;
         public void run()
              System.out.println("Printed by "+Thread.currentThread().getName()+" : "+builder.append(" output:5"));
    public static void main(String s[])
         builder.append(" output:2");
         Two d1=new Two(builder);
         Thread t1=new Thread(d1);
         Thread t2=new Thread(d1);
         Thread t3=new Thread(d1);
         t1.start();
         t2.start();
         t3.start();
         builder.append(" output:3");
         builder.append(" output:4");
         System.out.println("Printed by "+Thread.currentThread().getName()+" : "+builder);
    when the program is executed it show different output in corresponds to the order of call and it is not showing thread saftey.

    thanks tolls ,
    below is my output : -
    first time when i run the progra"_
    Printed by Thread-1 : output:1 output:2 output:5 output:5 output:5
    Printed by Thread-0 : output:1 output:2 output:5
    Printed by main : output:1 output:2 output:5 output:5 output:5 output:3 output:4
    Printed by Thread-2 : output:1 output:2 output:5 output:5
    second time when i run the program_
    Printed by Thread-0 : output:1 output:2 output:5
    Printed by Thread-2 : output:1 output:2 output:5 output:5 output:3 output:4 output:5
    Printed by Thread-1 : output:1 output:2 output:5 output:5
    Printed by main : output:1 output:2 output:5 output:5 output:3 output:4
    see the order of output. there is no synchronization among threads . Where as StringBuffer is thread safe but the order of output is different at each time. My question is just that
    how to achieve synchronization among threads.

  • TS2002 using a multi-port adapter to increase the number of USB ports - affects system functioning?  Port priority?  In advance, I send my thanks!

    Hello.  I've never "started a discussion" before.  Ah well I've always had good luck with the communities so here goes.  Today I plugged a Belkin multi-port adapter into my MacBook Pro running OS X Version 10.6.8  This enabled me to plug in my keyboard; mouse and printer.   Yes after two years I wanted to be back to an independent full keyboard and mouse.  BUT ALAS!  Now the little spinning wheel keeps appeariing while I'm on the Internet and I learned through my "Help" app that I have "slow start-up, pausing at Initializing network or "Configuring network time"  (sounds like some of the men I've dated).
    Could it be the multi-port adapter?  Should I use a different model?  The abiltiy to have the printer; keyboard and mouse all connected at the same time is important to my work. 
    In advance, I send my thanks!
    Jeannie-Marie

    I think it is the server socket which controls the number of client sockets to be opened. The number of connections that are accepted by the server socket is called the backlog of server socket. By default its value is 50. (See java.net.ServerSocket class in java docs)...
    we can specify the backlog in the constructor of server socket...
    ~pacific

  • HT4623 With the new update, how do I exit out of a game, photos whatever I've been using, so they aren't running in the background

    Usually you hold on the button &amp; they jiggle, they don't with the update

    Double-click the Home button and swipe up on the screen image of the App that you want to remove.

  • Not the "run of the mill" receiving mail issue...

    I've been having this issue for months - I would say at least 4-6 months. At one point I worked one-on-one with someone from Apple over the phone to try to fix it, but it was still never resolved.
    I have our email set up so that on the left-hand side, the view shows the list of folders and then below that, a small "Mail Activity" window. While working on the computer - which is usually anywhere from 10-14 hours per day, I will notice when an email comes in that the Mail Activity window it will say "Incoming Messages 1 of 3" (or however many).
    Well, sometimes 3 messages really do come, but other times, only 1 out of the 3 come or other times, none come. The Activity Window will say there are incoming messages, but I will get none.
    This would be just a nuisance, except I think discovered I wasn't getting email messages from people - and that seemed to be random, I'd be emailing back and forth with a friend and she'd mention that I "skipped" an email, it would turn out that for some reason I didn't get one, even though I was getting the other ones from her at the time. And it was multiple people, from all different email addresses, etc.
    I don't have any other email address other than the @mac.com one we have.
    I did notice one day while just looking around (didn't move, delete or alter anything) that the number of email messages in /Users/myname/Library/Mail/Mac-myemail/INBOX.imapmbox/Messages is different than the number of messages actually in my "Inbox" - not sure if it should be the same?? Like right now, I have 1665 emails in my inbox, but in that 'Messages' folder, it has 1917 items.
    Oh, and when I was working the Apple person, they did have me rebuild the mailbox several times.
    Sorry for the long post, I REALLY appreciate any help anyone can give me???
    Thank you!

    Your ".mac" account has been set up to use IMAP for receiving emails. As someone who has been using IMAP with Mail for about 2 years I can tell you from experience that when it says you are receiving "1 of 3" emails, it doesn't mean you are receiving 3 NEW emails. It means that it is updating 3 emails. Sometimes it says receiving "1 of 645".
    The truth is, the numbers don't really matter. That also goes for the number of messages in your inbox. Just because the number of messages don't match up doesn't mean the messages have been lost. They are just in other places, they may have been deleted, they could be in the sent folder, they could be in your drafts folder, junk folder, etc.
    The tech person you spoke to was correct in what he did. The only numbers that should ever be matching up are the numbers at me.com with the numbers in your inbox. As long as those are the same, you are not losing emails.
    However, anything is possible and I urge you to ask your friends to send you 10 or 20 "test emails" to make sure everything is running smoothly. If you are actually missing emails, that is an error beyond your control. That would be a problem on the servers at Apple and you would probably have to call or contact a Mobile Me representative.

  • Using multi-thread in RMI

    i know how to do a simple RMI program, but now i want to have a multi-threaded server to support the client. could any one tell me how to do this (using Thread in RMI) ??
    thx.
    Mo

    Well, you kind of answered your own question.
    An RMI server is inherently multi-threaded. This means that each remote request from a client is a separate thread, and can execute simultaneously with requests from other clients. In fact, your biggest problem will probably be to identify the places where access to objects must be synchronized, so that simultaneous requests do not conflict.
    So what is it you have to do that RMI doesn't do?

  • Acrobat 9 Pro Extended Distiller - Multi-threaded?

    I am using distiller on some fairly large postscript files (also large numbers of small postscript files) and am running into what appears to be machine limitations. I'm running on a 32 bit workstation with 3gb RAM and an intel core duo CPU. Looking at the perf monitor, my processes are not RAM limited and I never seem to get the CPU use above 50% which indicates to me that distiller may not be multi-threaded. Is that the case? If so, is there a way to get distiller to use both CPUs? (or all 4 on a quad core)

    I am also facing the same issue. Although you can run multiple instances of Distiller using switch "N"
    acrodist.exe -N
    But don't know how to distribute the watchedFolders among them.
    Even though you can specify the Watch Folders once the instances are up and running.. but in case if you close the instances and start them again.. only one instance will have all the watched folders with it.
    So don't know the solution to this, anyone pls help
    Thanks in Advance
    Naveen Sharma

  • Help! My application uses a Single Thread !

    Hi all !
    I have a web application which performs some long running tasks. This can be easily simulated with:
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              System.out.println("Started Long Running Task!");
              try {
                   Thread.sleep(20000);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              System.out.println("Done");
    In order to deal with Long Running Tasks, I have created a WorkManager with MinThreads 10 and MaxThreads 100
    Then I have assigned the Work Manager to the Web application usign weblogic.xml:
    <?xml version="1.0" encoding="UTF-8"?>
    <weblogic-web-app xmlns="http://www.bea.com/ns/weblogic/90">
    <wl-dispatch-policy>WorkManager-0</wl-dispatch-policy>
    </weblogic-web-app>
    However it seems that the Web application uses a SINGLE Thread to reply to the Servlet. In other words issuing n parallel requests the output is:
    Started Long Running Task!
    [20 Seconds Pause]
    Started Long Running Task!
    [20 Seconds Pause]
    Started Long Running Task!
    [20 Seconds Pause]
    Started Long Running Task!
    [20 Seconds Pause]
    My settings are the default Weblogic 12c Server settings, I've just added Weblogic NIO performance libs to the Java's path.
    Is there any setting which allow just 1 Socket for my application ? Maybe it's because I'm using the "unlicensed" (free download) server version ?
    Thanks a lot
    Frank

    You need to create separate Windows user accounts if you want to seperate the behaviour of iTunes for each user. That also means separate iTunes libraries for each user.
    Windows is a multi-user operating system but you are not using it properly. iTunes is not a multi-user application. No application is. You can't expect it to treat different users differently when they are all using the same computer user account.
    Do you understand what I mean?

  • Multi-Thread application and common data

    I try to make a multi-Thread application. All the Threads will update some common data.
    How could I access the variable �VALUE� with the Thread in the following code:
    public class Demo {
    private static long VALUE;
    public Demo(long SvId) {
    VALUE = 0;
    public static class makeThread extends Thread {
    public void run() {
    VALUE++;
    public static long getVALUE() {
    return VALUE;
    The goal is to get the �VALUE� updated by the Thread with �getVALUE()�
    Thanks for your reply
    Benoit

    That code is so wrong in so many ways......
    I know you're just experimenting here, learning what can and can't be done with Threads, but bad habits start early, and get harder to kick as time goes on. I am going to give a little explanation here about what's wrong, and what's right.. If you're going to do anything serious though, please, read some books, and don't pick up bad habits.
    Alright, The "answer" code. You don't use Thread.sleep() to wait for Threads to finish. That's just silly, use the join() method. It blocks until the threads execution is done. So if you have a whole bunch of threads in an array, and you want to start them up, and then do something once they finish. Do this.
    for(int k=0; k<threads.length; k++) {
      threads[k].start();
    for(int k=0; k<threads.length; k++) {
      threads[k].join();
    System.out.println("All Threads Done");Now that's the simple problem. No tears there.
    On to the java memory model. Here where the eye water starts flowing. The program you have written is not guarenteed to do what you expect it to do, that is, increment VALUE some amount of time and then print it out. The program is not "Thread Safe".
    Problem 1) - Atomic Operations and Synchronization
    Incrementing a 'long' is not an atomic operation via the JVM spec, icrementing an int is, so if you change the type of VALUE to an int you don't have to worry about corruption here. If a long is required, or any method with more then one operation that must complete without another thread entering. Then you must learn how to use the synchronized keyword.
    Problem 2) - Visiblity
    To get at this problem you have to understand low level computing terms. The variable VALUE will NOT be written out to main memory every time you increment it. It will be stored in the CPUs cache. If you have more then one CPU, and different CPUs get those threads you are starting up, one CPU won't know what the other is doing. You get memory overwrites, and nothing you expect. If you solve problem 1 by using a synchronized block, you also solve problem 2, because updating a variable under a lock will cause full visiblity of the change. However, there is another keyword in java.. "volatile".. A field modified with this keyword will always have it's changes visible.
    This is a very short explaination, barely scratching the surface. I won't even go into performance issues here. If you want to know more. Here's the resources.
    Doug Lea's book
    http://java.sun.com/docs/books/cp/
    Doug Lea's Site
    http://g.cs.oswego.edu
    -Spinoza

  • InfoPath: the multi-threading challenge

    Or to be more specific: calling a DataSource from a different thread.
    A project I'm working on includes an InfoPath form in which some heavy duty tasks are executed. These tasks can take over 10+ seconds to execute. To avoid the GUI to get stuck during execution, multi-threading is implemented. The problem lies in providing
    feedback to the user. Several methods have been used, but all end in the exceptions shown below.
    Unlike WinForms and such, InfoPath does not seem to provide a way to invoke the GUI. What we are trying to do is change field values to reflect the status of the process. This is done through the MainDataSource. I've tried several methods to call
    this datasource through another thread, like invoking a provided delegate, or execution context. However all these methods have similar results.
    When calling a method or property on the datasource the following exception is thrown:
    System.InvalidOperationException was unhandled
      Message="Operation is not valid due to the current state of the object."
      Source="Microsoft.Office.InfoPath.Client.Internal.Host"
      StackTrace:
           at Microsoft.Office.Interop.InfoPath.SemiTrust.ICLRExtensionsWrapper.IncrementSqmPoint(Int32 idDataPt)
           at Microsoft.Office.InfoPath.Internal.DataSourceHost.CreateNavigator()
           at Form1.FormCode.ContextCallbackMethod(Object obj) in E:\Projects\InfoPath Multithreading\Source\Form1\FormCode.cs:line 74
           at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
           at Form1.FormCode.ThreadMethod(Object myParamsObj) in E:\Projects\InfoPath Multithreading\Source\Form1\FormCode.cs:line 68
           at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
           at System.Threading.ThreadHelper.ThreadStart(Object obj)
    This seems to indicate the DataSource is locked for some reason. Even the ReadOnly property can not be read.
    When calling the SetValue method on an XPathNavigator provided by a datasource and passed through another thread, the following exception is thrown:
    System.AccessViolationException was unhandled
      Message="Attempted to read or write protected memory. This is often an indication that other memory is corrupt."
      Source="Microsoft.Office.InfoPath.Client.Internal.Host.Interop"
      StackTrace:
           at Microsoft.MsoOffice.InfoPath.MsxmlInterop.NativeHelpers.SetText(IXMLDOMNode* , Char* )
           at Microsoft.MsoOffice.InfoPath.MsxmlInterop.MsxmlNodeImpl.set_Text(String strText)
           at Microsoft.Office.InfoPath.MsxmlNavigator.SetValue(String value)
           at Form1.FormCode.DelegateMethod(XPathNavigator nav) in E:\Projects\InfoPath Multithreading\Source\Form1\FormCode.cs:line 81
           at Form1.FormCode.ThreadMethod(Object myParamsObj) in E:\Projects\InfoPath Multithreading\Source\Form1\FormCode.cs:line 70
           at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
           at System.Threading.ThreadHelper.ThreadStart(Object obj)
    I have searched through the internet but am unable to find any useful information about this subject. There are only a few weeks remaining before the deadline. A work-around has been implemented, but since it requires additional active user interaction
    it is far from ideal. I hope you can help me in finding a solution.

    For anyone who is still interested all this time later....
    I wouldn't use a Dispatcher in InfoPath simply because InfoPath requires .Net 2.0 only and Dispatcher was not added until .Net 3.0 which means you would have to enforce installation of .Net 3.0 yourself.
    There is an easy alternative which is SynchronizationContext (more specifically a WindowsFormsSynchronizationContext).
    Also I suggest you do not use ThreadStart but rather use one of the more modern and well known threading paradigms. A good alternative is a BackgroundWorker.
    e.g.
    private BackgroundWorker _Worker;
    public void InternalStartup()
    InitializeWorker();
    ((ButtonEvent)EventManager.ControlEvents["Button"]).Clicked += new ClickedEventHandler(ButtonClick);
    public void InitializeWorker()
    _Worker = new BackgroundWorker();
    _Worker.WorkerReportsProgress = true;
    _Rorker.WorkerSupportsCancellation = true;
    _Worker.DoWork += new DoWorkEventHandler(_Worker_DoWork);
    _Worker.ProgressChanged += new ProgressChangedEventHandler(_Worker_ProgressChanged);
    _Worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_Worker_RunWorkerCompleted);
    public void ButtonClick(object sender, ClickedEventArgs e)
    if (_Worker.IsBusy)
    _Worker.CancelAsync();
    else
    // Very important to include this line!
    AsyncOperationManager.SynchronizationContext = new WindowsFormsSynchronizationContext();
    _Worker.RunWorkerAsync();
    void _Worker_DoWork(object sender, DoWorkEventArgs e)
    // Do stuff in another thread and report back to the UI thread.
    object state;
    int percentage = 0;
    _Worker.ReportProgress(percentage, state).
    public void _Worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
    // This is called on the thread that started the worker.
    // In this case the UI thread which means it is safe to use the MainDataSource.
    CreateNavigator().SelectSingleNode("my:Main/my:Progress", NamespaceManager).SetValue(e.ProgressPercentage);
    void _Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    // Do anything you want to do on completion here.
    One thing of note is that the SynchronizationContext in InfoPath for some reason or other always seems to be Null. The result is that when you call RunWorkerAsync() it captures the current synchronization context (null) which means the default is used and
    a ProgressChanged is called on a new thread each time. To prevent this we need to manually set the context before calling RunWorkerAsync() which is done using the AsyncOperationManager.

Maybe you are looking for

  • Very important Battery Question from a prospective Mac buyer...

    Hi, guys! I am thinking of purchasing a Macbook Pro and just read that the battery is sealed-in. I know that I am able to buy a replacement battery, but I would also like to find out if I can still use the Pro even after the battery is broken? I have

  • SIDADM do not have enough previlages to startsap after DB2 upgrade to 9.5

    Hello Anyone, I recently upgrade our DB2 version from 8.X to 9.5.2, We run SAP netweaver ECC 5  with DB2.  I can startsap if I do db2start and and then issue a startsap after su to sidadm. Please can anyone advice I had followed all instruction of th

  • How do I have iTunes automatically download pre-orders?

    Hello, I selected "Automatically download pre-orders when available" under iTunes > Preferences > Store Preferences and yet the automatic download only happens if I re-open iTunes. If, for example, I open iTunes on Monday (and keep it running) and on

  • Component replacing installing Visual C++ 2005 SP1 Redistributable

    In starting tsManager.exe if any error like "The application has failed to start because its side-by-side configuration is incorrect" is faced, Solution given in ReadMe.txt file of Transformation server is to install "Microsoft Visual C++ 2005 SP1 Re

  • Newsletter issues

    What settings do I need to get Pages to treat each of my 8 pages in my newsletter as an individual page? Right now the first page stays put, but whatever I add to a subsequent page moves everything on the 7 pages that follow. Also, in my last issue,