Setjmp/longjmp, threads and bdb

We are developing a multithreaded transactional server in C that
uses bdb. We are considering an exception handling mechanism based
on setjmp/longjmp. The intention is to centralize error handling,
including database-related errors. We were wondering if other bdb users
have had experience with bdb/multi-threading/setjmp,longjmp?
Are there any interactions we should be weary of?
Thanks,
Guy

geert3 wrote:
I was facing the same problem: JNI function calls longjmp, then VM aborts when exiting from JNI function back into Java.
Turns out to be a problem in Java, see http://bugs.sun.com/bugdatabase/view_bug.do%3Bjsessionid=43ac0833a910963aef55e681c2cd?bug_id=6649401
I give up. How does that bug or the one that was actually fixed (since that was a duplicate) fix anything at all associated with longjmp?
Not to mention of course that using setjmp/longjmp in C correctly is something that requires very, very careful coding. I certainly wouldn't consider it likely nor even reasonable for it to work when crossing boundaries with even relatively simple third party invocations and certainly not something like java.

Similar Messages

  • A problem with Threads and MMapi

    I am tring to execute a class based on Game canvas.
    The problem begin when I try to Play both a MIDI tone and to run an infinit Thread loop.
    The MIDI tone "Stammers".
    How to over come the problem?
    Thanks in advance
    Kobi
    See Code example below:
    import java.io.IOException;
    import java.io.InputStream;
    import javax.microedition.lcdui.Graphics;
    import javax.microedition.lcdui.Image;
    import javax.microedition.lcdui.game.GameCanvas;
    import javax.microedition.media.Manager;
    import javax.microedition.media.MediaException;
    import javax.microedition.media.Player;
    public class MainScreenCanvas extends GameCanvas implements Runnable {
         private MainMIDlet parent;
         private boolean mTrucking = false;
         Image imgBackgound = null;
         int imgBackgoundX = 0, imgBackgoundY = 0;
         Player player;
         public MainScreenCanvas(MainMIDlet parent)
              super(true);
              this.parent = parent;
              try
                   imgBackgound = Image.createImage("/images/area03_bkg0.png");
                   imgBackgoundX = this.getWidth() - imgBackgound.getWidth();
                   imgBackgoundY = this.getHeight() - imgBackgound.getHeight();
              catch(Exception e)
                   System.out.println(e.getMessage());
          * starts thread
         public void start()
              mTrucking = true;
              Thread t = new Thread(this);
              t.start();
          * stops thread
         public void stop()
              mTrucking = false;
         public void play()
              try
                   InputStream is = getClass().getResourceAsStream("/sounds/scale.mid");
                   player = Manager.createPlayer(is, "audio/midi");
                   player.setLoopCount(-1);
                   player.prefetch();
                   player.start();
              catch(Exception e)
                   System.out.println(e.getMessage());
         public void run()
              Graphics g = getGraphics();
              play();
              while (true)
                   tick();
                   input();
                   render(g);
          * responsible for object movements
         private void tick()
          * response to key input
         private void input()
              int keyStates = getKeyStates();
              if ((keyStates & LEFT_PRESSED) != 0)
                   imgBackgoundX++;
                   if (imgBackgoundX > 0)
                        imgBackgoundX = 0;
              if ((keyStates & RIGHT_PRESSED) != 0)
                   imgBackgoundX--;
                   if (imgBackgoundX < this.getWidth() - imgBackgound.getWidth())
                        imgBackgoundX = this.getWidth() - imgBackgound.getWidth();
          * Responsible for the drawing
          * @param g
         private void render(Graphics g)
              g.drawImage(imgBackgound, imgBackgoundX, imgBackgoundY, Graphics.TOP | Graphics.LEFT);
              this.flushGraphics();
    }

    You can also try to provide a greater Priority to your player thread so that it gains the CPU time when ever it needs it and don't harm the playback.
    However a loop in a Thread and that to an infinite loop is one kind of very bad programming, 'cuz the loop eats up most of your CPU time which in turn adds up more delays of the execution of other tasks (just as in your case it is the playback). By witting codes bit efficiently and planning out the architectural execution flow of the app before start writing the code helps solve these kind of issues.
    You can go through [this simple tutorial|http://oreilly.com/catalog/expjava/excerpt/index.html] about Basics of Java and Threads to know more about threads.
    Regds,
    SD
    N.B. And yes there are more articles and tutorials available but much of them targets the Java SE / EE, but if you want to read them here is [another great one straight from SUN|http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html] .
    Edited by: find_suvro@SDN on 7 Nov, 2008 12:00 PM

  • Problem with threads and ProgressMonitor

    Dear Friends:
    I have a little problem with a thread and a ProgressMonitor. I have a long time process that runs in a thread (the thread is in an separate class). The thread has a ProgressMonitor that works fine and shows the tasks progress.
    But I need deactivate the main class(the main class is the user interface) until the thread ends.
    I use something like this:
    LongTask myTask=new LongTask();
    myTask.start();
    myTask.join();
    Now, the main class waits for the task to end, but the progress monitor don`t works fine: it shows only the dialog but not the progress bar.
    What's wrong?

    Is the dialog a modal dialog? This can block other UI updates.
    In general, you should make sure that it isn't modal, and that your workThread has a fairly low priority so that the UI can do its updating

  • Having a problem with threads and using locks

    I was hoping someone could give me some hits on getting my code to run properly. The problem I am having is I think my locks and unlocks are not working properly. Plus, for some reason I always get the same output, which is:
    Withdrawal Threads         Deposit Threads            Balance
    Thread 2 attempts $29 Withdrawal - Blocked - Insufficient Funds
    Thread 4 attempts $45 Withdrawal - Blocked - Insufficient Funds
    Thread 6 attempts $34 Withdrawal - Blocked - Insufficient Funds
    Thread 7 attempts $40 Withdrawal - Blocked - Insufficient Funds
                                    Thread 1 deposits $187          $187
                                    Thread 3 deposits $169          $356
                                    Thread 5 deposits $61           $417
    Press any key to continue...If someone can see the error I made and doesn't mind explaining it to me, so I can learn from it, I would appreciate that very much.
    /************Assign2_Main.java************/
    import java.util.concurrent.*;
    public class Assign2_Main
    {//start Assign2_Main
        public static void main(String[] args)
        {//start main
               // create ExecutorService to manage threads
               ExecutorService threadExecutor = Executors.newCachedThreadPool();
            Account account = new SynchronizedThreads();
            Deposit deposit1 = new Deposit(account, "Thread 1");
            Deposit deposit2 = new Deposit(account, "Thread 3");
            Deposit deposit3 = new Deposit(account, "Thread 5");
            Withdrawal withdrawal1 = new Withdrawal(account, "Thread 2");
            Withdrawal withdrawal2 = new Withdrawal(account, "Thread 4");
            Withdrawal withdrawal3 = new Withdrawal(account, "Thread 6");
            Withdrawal withdrawal4 = new Withdrawal(account, "Thread 7");
            System.out.println("Withdrawal Threads\t\tDeposit Threads\t\t\tBalance");
            System.out.println("------------------\t\t---------------\t\t\t-------\n");
            try
                threadExecutor.execute(withdrawal1);       
                threadExecutor.execute(deposit1);     
                threadExecutor.execute(withdrawal2);  
                threadExecutor.execute(deposit2);    
                threadExecutor.execute(withdrawal3);
                threadExecutor.execute(deposit3);       
                threadExecutor.execute(withdrawal4);
            catch ( Exception e )
                 e.printStackTrace();
                //shutdown worker threads
               threadExecutor.shutdown();
        }//end main
    }//end Assign2_Main/******************Withdrawal.java****************************/
    public class Withdrawal implements Runnable
    {//start  class Withdrawal
          *constructor
        public Withdrawal(Account money, String n)
             account = money;
             name = n;
        public void run()
        {//start ruin
             int newNum = 0;
                newNum = account.getBalance(name); 
               Thread.yield();
        }//end run
        private Account account;
        private String name;
    }//end  class Withdrawal/*******************Deposit.java***************/
    import java.util.Random;
    public class Deposit implements Runnable
    {//start class Deposit
          *constructor
        public Deposit(Account money, String n)
             account = money;
             name = n;
        public void run()
        {//start run
                try
                     Thread.sleep(100);
                   account.setBalance(random.nextInt(200), name);
                }// end try
                catch (InterruptedException e)
                  e.printStackTrace();
       }//end run
       private Account account;
       private Random random = new Random();
       private String name;
    }//end class Deposit/********************Account.java*****************/
    *Account interface specifies methods called by Producer and Consumer.
    public interface Account
         //place sum into Account
         public void setBalance(int sum, String name);
         //return  value of Account
            public int getBalance(String name);         
    } /**************SynchronizedThreads.java****************/
    import java.util.concurrent.locks.*;
    import java.util.Random;
    public class SynchronizedThreads implements Account
    {//start SynchronizedThreads
          *place money into buffer
        public void setBalance(int amount, String name)
        {//start setBalance
             // lock object
             myLock.lock();           
            sum += amount;
            System.out.println("\t\t\t\t" + name + " deposits $" + amount +"\t\t$"+ sum+"\n");       
               //threads are singnaled to wakeup
            MakeWD.signalAll();
              // unlock object                                                
            myLock.unlock();
           }//end setBalance
            *gets the balance from buffer
           public int getBalance(String name)
        {//start getBalance
             int NewSum = random.nextInt(50);
             //lock object
            myLock.lock();
            try
                 if(sum > NewSum)
                     //takes NewSum away from the account
                     sum -= NewSum;
                        System.out.println(name + " withdraws $" + NewSum +"\t\t\t\t\t\t$"+ sum+"\n");
                else
                     System.out.println(name +  " attempts $" + NewSum + " Withdrawal - Blocked - Insufficient Funds\n");                 
                     //not enough funds so thread waits
                        MakeWD.await();         
                //threads are singnaled to wakeup
                MakeD.signalAll();     
                }//end try
            catch (InterruptedException e)
                   e.printStackTrace();
            finally
                 //unlock object
                 myLock.unlock();
            return NewSum;     
         }//end getBalance
         private Random random = new Random();  
         private Lock myLock = new ReentrantLock();
         private Condition MakeD = myLock.newCondition();
         private Condition MakeWD = myLock.newCondition();
         private int sum = 0;
    }//end SynchronizedThreads

    You can also try to provide a greater Priority to your player thread so that it gains the CPU time when ever it needs it and don't harm the playback.
    However a loop in a Thread and that to an infinite loop is one kind of very bad programming, 'cuz the loop eats up most of your CPU time which in turn adds up more delays of the execution of other tasks (just as in your case it is the playback). By witting codes bit efficiently and planning out the architectural execution flow of the app before start writing the code helps solve these kind of issues.
    You can go through [this simple tutorial|http://oreilly.com/catalog/expjava/excerpt/index.html] about Basics of Java and Threads to know more about threads.
    Regds,
    SD
    N.B. And yes there are more articles and tutorials available but much of them targets the Java SE / EE, but if you want to read them here is [another great one straight from SUN|http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html] .
    Edited by: find_suvro@SDN on 7 Nov, 2008 12:00 PM

  • Java threads and WinLogon processes taking CPU!

    We are seeing a strange problem. We have a multi-threaded java application
    that is deployed on a Microsoft Windows 2000 server (SP4) with Citrix
    Metaframe XP (Feature release 2). When this application starts, we start to see
    multiple WINLOGON.EXE processes (20 plus) each taking up 1-2% of CPU -
    this raises the CPU usage on the server significantly, impacting performance.
    We have tested with JDK 1.3, 1.4, and 1.5 and see the same issues. If we
    run the java application in a single thread, we dont see the same issue.
    Has any one seen this problem before? Any suggestion on how this can be resolved?
    Thanks in advance!

    Thanks for your replies. This is a Citrix environment where there are 50 plus
    users logged in and there are 50 plus instances of Winlogon.exe always
    running. Most of the time the cpu usage of these processes is 0.
    We tried a multi-threaded program that lists files in a directory every few
    seconds. There are 40 plus servers in the farm that we are deploying this
    application on. We are seeing this problem on only some of the servers.
    If we run a single thread from main(), we dont see the issue. But if we spawn
    10 threads doing the scans periodically, we notice that as soon as all the threads
    start, the WinLogons appear to start to take up CPU. When we stop the java
    program, the WinLogon processes drop in CPU usage.
    Is it possible that Java and WinLogon share some dlls that could be triggering
    the WinLogon processes off?
    We have tried running the single thread and multi-threaded programs around
    same time and the correlation with the winlogons is clearly visible. If we add
    sleep() soon after we start a thread, the winlogons seem to kick in later.

  • Handling Threads and Memory

    I'm sorry if this is a cross post to my StringBuffer problem. I have run a test that instantiates the object in question and the memory gets collected so I don't think it's that. My question is on how memory pertaining to Threads is handled.
    In my application I have a Thread array that launches X number of Threads. Currently 5. When an object wants a job run, the static Thread pool looks at the current thread and sees if it is still working. If it is, we sleep until it is available. Then I give it another job to do, start it, and move to the next thread.
    Question 1 -
    In a Thread [] is it better to replace the Thread at position x as in
    threads[a] = new Thread();
    threads[a].start();
    or is it better to change some parameter in the thread and then call
    start() again?
    Question 2 -
    I am currently using the second method. In my Thread object I have a MessageObject which contains a StringBuffer, which is eating memory. These MessageObject's are increasing. Some are being collected but many are staying live in the system and causing a memory error. When I do the following....
    MyThread.MessageObject = new MessageObject()
    That should make the original object available for cleanup right?
    Should I call finalize on the MessageObject before replacing it?
    Thanks you for any insights.

    If you want to use thread pools, and you can use JDK 5.0 (formerly known as J2SDK 1.5, codename Tiger), try using the java.util.concurrent package instead of writing your own thread pool (it's really difficult to make a thread pool right).
    If you can't use JDK 5.0, you can try the original util.concurrent package ( http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/intro.html ) from Doug Lea. It's used in the JBoss Application Server, so it's tested and reliable.
    If you need to use an object pool, try using the Commons Pool Component from Jakarta Apache: http://jakarta.apache.org/commons/pool/

  • HT4847 I have a new iphone and cannot delete the backup from icloud.  It says that it is in use.  I have read some of the other threads and it only seems to be haphazard solutions. Is there a definite way to fix this? I am not able to change icloud accoun

    I have a new iphone and cannot delete the backup from icloud.  It says that it is in use.  I have read some of the other threads and it only seems to be haphazard solutions. Is there a definite way to fix this? I am not able to change icloud accounts.

    Follow the steps in wjosten's post here: https://discussions.apple.com/message/13356770#13356770 (for Windows, substitute Outlook in step 2).

  • Problem with Thread and InputStream

    Hi,
    I am having a problem with threads and InputStreams. I have a class which
    extends Thread. I have created and started four instances of this class. But
    only one instance finishes its' work. When I check the state of other three
    threads their state remains Runnable.
    What I want to do is to open four InputStreams which are running in four
    threads, which reads from the same url.
    This is what I have written in my thread class's run method,
    public void run()
         URL url = new URL("http://localhost/test/myFile.exe");
    URLConnection conn = url.openConnection();
    InputStream istream = conn.getInputStream();
    System.out.println("input stream taken");
    If I close the input stream at the end of the run method, then other threads
    also works fine. But I do not want to close it becuase I have to read data
    from it later.
    The file(myFile.exe) I am trying to read is about 35 MB in size.
    When I try to read a file which is about 10 KB all the threads work well.
    Plz teach me how to solve this problem.
    I am using JDK 1.5 and Win XP home edition.
    Thanks in advance,
    Chamal.

    I dunno if we should be doing such things as this code does, but it works fine for me. All threads get completed.
    public class ThreadURL implements Runnable
        /* (non-Javadoc)
         * @see java.lang.Runnable#run()
        public void run()
            try
                URL url = new URL("http://localhost:7777/java/install/");
                URLConnection conn = url.openConnection();
                InputStream istream = conn.getInputStream();
                System.out.println("input stream taken by "+Thread.currentThread().getName());
                istream.close();
                System.out.println("input stream closed by "+Thread.currentThread().getName());
            catch (MalformedURLException e)
                System.out.println(e);
                //TODO Handle exception.
            catch (IOException e)
                System.out.println(e);
                //TODO Handle exception.
        public static void main(String[] args)
            ThreadURL u = new ThreadURL();
            Thread t = new Thread(u,"1");
            Thread t1 = new Thread(u,"2");
            Thread t2 = new Thread(u,"3");
            Thread t3 = new Thread(u,"4");
            t.start();
            t1.start();
            t2.start();
            t3.start();
    }And this is the o/p i got
    input stream taken by 2
    input stream closed by 2
    input stream taken by 4
    input stream closed by 4
    input stream taken by 3
    input stream closed by 3
    input stream taken by 1
    input stream closed by 1
    can u paste your whole code ?
    ram.

  • Iphone 5 - I am trying to delete message threads and once I do, I go to text someone else and it won't send. HELP? I just don't want those messages on my phone anymore.

    Iphone 5 - I am trying to delete message threads and once I do, I go to text someone else and it won't send. HELP? I just don't want those messages on my phone anymore. I have tried to restart my phone but when I do, the "deleted" threads show back up on my phone. I use iOS 7.1.

    Hello Makayla,
    It sounds like you're deleted message threads keep coming back after you restart the devie. I recommend starting by quitting all the running apps on your phone:
    iOS: Force an app to close
    Double-click the Home button.
    Swipe left or right until you have located the app you wish to close.
    Swipe the app up to close it. 
    When you have done that restart the device and test the issue again:
    iOS: Turning off and on (restarting) and resetting
    If the issue persists, backup your device to iTunes and then restore it as a new device and verify that it works. 
    How to erase your iOS device and then set it up as a new device or restore it from backups
    If it does, then restore your backup to either verify it still works and the software just needed reinstalled, or isolate the issue to the backup file itself. 
    Thank you for using Apple Support Communities.
    Regards,
    Sterling

  • Little bit of thread and little bit of instant messenger design problem

    OK! i have a small problem here, i am planning on making a instant messenger server and client, not compatible with any out there(as of yet) and not using any stansard protocols out there, just something i made on my own. ok now the problem i am trying to figure out is....i have a "Messaging Server" as the name suggests it sends messages from one client to the other, how it is setup is, client connects to this server, the server accepts and creates a new thread for this client and adds a message listener to this client handler thread. as and when the server creates this thread for the client, it puts it in a vector which is keeping track of every client connected to this server. so now when the client sends a message to another client, basically it goes through this server, the thread upon receiving this message, fires a method of the listener. this method takes the message, finds out who it is going to(therefore the userid) and seaches the threads vector to find the appropriate thread and then just creats another striped down message out of the received message and calls a method in that thread to send this newly created message and hence the message should be sent.(i am speculating, i still have not created this)
    so the problem ia m logically facing is...at what point of time who is taking the load, what i mean by that is, when the thread receives the message, ofcourse it is this thread which is working is taking the load, but when the listener fucntion is fired which thread is handlign the call is it the client handler thread which fired the method or the messaging server thread which creates these threads?? now once that is solved, who(which thread) is doing the work when i call the fucntion in the other thread which i found aftre searching the vector. i mean i am thinking like this cuz i am not much in sink with the way threads work. i am also trying to figure out this to find out the load the server or the threads will be having.
    algo example:
    class messageServer
         vector currentWorkingThreads;
         messageListener listener;
         main()
              listener = new messageListener(); //should it be here or the other place i am mentioning below
              while(true)
                   clientHandler = socket.accept();
                   listener = new messageListener(); //should it be here or the other place i am mentioning above
                   //create a thread and add this thread object to the vector
                   thread.addLisenter(listener);
    class messageServerThread
         string userid;
         messageListener lis;
         run()
              object obj = in.readObject();
              lis.sendMessage(obj);
         sendMessage(obj)
              out.writeObject(obj);
              out.flush;
    class messageListener
         sendMessage(msSendMessage msg)
              //find the appropriate user thread
              loop(currentWorkingThread.next())
                   messageServerThread msgThread = (messageServerThread)currentWorkingThread.element();
                   if(msg.userid == msgThread.userid)
                        msReceiveMessage rcvMsg = msg.strip(); //dosent matter what this does, it just strips the unwanted info and returns the type msReceiveMessage
                        msgThread.sendMessage(rcvMsg);
    and if this is something out of the line, or not a good way of doing it, can someone help me with the design it would be gr8.
    thanx a lot
    -Ankur
    help would be greatly appreciated.
    [email protected]

    other, how it is setup is, client connects to this
    server, the server accepts and creates a new thread
    for this client and adds a message listener to this
    client handler thread. as and when the server creates
    this thread for the client, it puts it in a vector
    which is keeping track of every client connected to
    this server.ok so far.
    so now when the client sends a message to
    another client, basically it goes through this server,
    the thread upon receiving this message, fires a method
    of the listener. this method takes the message, finds
    out who it is going to(therefore the userid) and
    seaches the threads vector to find the appropriate
    thread and then just creats another striped down
    message out of the received message and calls a method
    in that thread to send this newly created message andhere you seem to confuse the thread instance and the thread of execution. the thread invoking this method is still the event handling thread (i.e. the receiver thread of the socket). you do not need threads for delivering - this can be done by the receiving sockets' event handling threads. disadvantage: if processing of the message takes significant time then the socket is blocked and cannot process another message.
    solution: put the message in an event queue which is processed by one or more threads. (see my example i e-mailed you)
    robert
    hence the message should be sent.(i am speculating, i
    still have not created this)
    so the problem ia m logically facing is...at what
    point of time who is taking the load, what i mean by
    that is, when the thread receives the message,
    ofcourse it is this thread which is working is taking
    the load, but when the listener fucntion is fired
    which thread is handlign the call is it the client
    handler thread which fired the method or the messaging
    server thread which creates these threads?? now once
    that is solved, who(which thread) is doing the work
    when i call the fucntion in the other thread which i
    found aftre searching the vector. i mean i am thinking
    like this cuz i am not much in sink with the way
    threads work. i am also trying to figure out this to
    find out the load the server or the threads will be
    having.
    algo example:
    class messageServer
    vector currentWorkingThreads;
    messageListener listener;
    main()
    listener = new messageListener(); //should it be
    e here or the other place i am mentioning below
    while(true)
    clientHandler = socket.accept();
    listener = new messageListener(); //should it be
    be here or the other place i am mentioning above
    //create a thread and add this thread object to the
    he vector
    thread.addLisenter(listener);
    class messageServerThread
    string userid;
    messageListener lis;
    run()
    object obj = in.readObject();
    lis.sendMessage(obj);
    sendMessage(obj)
    out.writeObject(obj);
    out.flush;
    class messageListener
    sendMessage(msSendMessage msg)
    //find the appropriate user thread
    loop(currentWorkingThread.next())
    messageServerThread msgThread =
    =
    (messageServerThread)currentWorkingThread.element();
    if(msg.userid == msgThread.userid)
    msReceiveMessage rcvMsg = msg.strip(); //dosent
    ent matter what this does, it just strips the unwanted
    info and returns the type msReceiveMessage
    msgThread.sendMessage(rcvMsg);
    and if this is something out of the line, or not a
    good way of doing it, can someone help me with the
    design it would be gr8.
    thanx a lot
    -Ankur
    help would be greatly appreciated.
    [email protected]

  • Is it possible to create a thread and run it in background in nokia ??

    Is it possible to create a thread and run it in background in nokia series 40 mobile phones using j2me ??

    Probably a good question for ForumNokia. If you mean start up a thread and run in the background while your MIDlet UI does other things, then sure, why not. If you mean that you want to exit your MIDlet, but leave a thread running in the background, then I don't believe you can do this on series 40. S60 is another story since it supports multiple tasks.

  • Posting topic to more than one thread and in different categories...

    Is there anything in the TOU we can "refer" to when users post the same topic in more than one thread and to add to that, more then one category? Case in point: http://discussions.apple.com/thread.jspa?messageID=8806009#8806009 (This is just one example)
    Limnos had a valid point. If we had a section in the TOU we could copy/paste from, I think it would help if we could refer to authority, ie., TOU.
    Thanks!
    Carolyn

    I wouldn't get into too much of a flury about that with end users. Notify as needed and let the moderators decide if it needs to be deleted. A good rule of thumb is you want the discussions to have:
    Everyone should feel comfortable reading Submissions and participating in discussions.
    That's from Terms of Use.
    And then there is:
    You agree to not interfere with or disrupt the Site.
    I'm seeing that logically one can conclude directing users not to crosspost may be considering interference with the site. I may suggest someone post in another forum if a solution is not transparent in the forum they are using, but that's as far as I'm comfortable bending the rules.
    I'm trying hard to keep my thumbs away from the keyboard when I see duplicate posts.

  • High number of threads and high CPU usage on a single instance

    Without any apparent reason, in some moments of day the website reports an increment of the HTTP Queue Length from an average of 10/20 queued requests to 100/200 and more.
    In that period of time the Average Response Time increases but the number of the requests on the website don't. Even increasing the instances it doesn't help to resolve the problem (maybe it just reduced it).
    It seems that the problem is not related to the traffic on the site. This issue happens either when the traffic is high or low.
    The autoscaling works well, we don't have peak of traffic but always a slow increasing of requests and the CPU is always below the 50% (memory too). The issue is resolved by the swap of the site and sometimes it's resolve by itself after a while.
    What I discovered when the issue happens, is that there's an instance (just an instance only), that has an high number of threads and CPU usage on the W3WP.exe process and these values are above the mean than the other instances. Eg, instances are around
    50/60 threads and 10/20% of CPU, the instance with the problem has 200 threads and 50/60% of CPU. If I kill the W3WP process on that instance the issue is resolved. 
    I monitored the HTTP requests, I tried the website extension "Diagnostics as service" but I can't discover anything that can help me to understand the problem. Of course, there are many requests that go in timeout but it is a consequences of a
    unresponsive instance.
    On the web hosting plan there are only two sites: the production site and its staging which is used for update of the production only and it's always sleeping. Plus, no webjobs are running on this site.
    What can I do to gather useful information that can help me to understand the reason of this problem?
    Thank you!

    "Does the instance with the high counts receive more traffic than the other instances? Is it possible that the load balancer not
    working the way it should be?"
    How can I get that information? I can't see metrics for a specific instance
    "Does it always happen to the first instance?"
    I will check it better, but in the order given by the Processes panel it's the second instance which has the issue. The scaling is at 2 instances for the most part of the time (it's the minimum).
    Maybe one time it was the 3th instance but I'm not sure, I'll give it more attention.
    " How long do these moment last?"
    The time can be 10 to 30 minutes, but I fix it as soon as I see the problem. It's not the down-scaling to resolve it because in these situations the CPU as well is high so the scaling holds or increases the number of instances.
    "- How often do these moments occurs?"
    It occurs quite often, 2/4 times a week.

  • How do you monitor a background thread and update the GUI

    Hello,
    I have a thread which makes its output available on PipedInputStreams. I should like to have other threads monitor the input streams and update a JTextArea embedded in a JScrollPane using the append() method.
    According to the Swing tutorial, the JTextArea must be updated on the Event Dispatch Thread. When I use SwingUtilities.invokeLater () to run my monitor threads, the component is not redrawn until the thread exits, so you don't see the progression. If I add a paint () method, the output is choppy and the scrollbar doesn't appear until the thread exits.
    Ironically, if I create and start new threads instead of using invokeLater(), I get the desired result.
    What is the correct architecture to accomplish my goal without violating Swing rules?
    Thanks,
    Brad
    Code follows:
    import java.lang.*;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.*;
    import java.awt.event.*;
    public class SystemCommand implements Runnable
         private String[] command;
         private PipedOutputStream pipeout;
         private PipedOutputStream pipeerr;
         public SystemCommand ( String[] cmd )
              command = cmd;
              pipeout = null;
              pipeerr = null;
         public void run ()
              exec ();
         public void exec ()
              // --- Local class to redirect the process input stream to a piped output stream
              class OutputMonitor implements Runnable
                   InputStream is;
                   PipedOutputStream pout;
                   public OutputMonitor ( InputStream i, PipedOutputStream p )
                        is = i;
                        pout = p;
                   public void run ()
                        try
                             int inputChar;
                             for ( ;; )
                                  inputChar = is.read();
                                  if ( inputChar == -1 ) { break; }
                                  if ( pout == null )
                                       System.out.write ( inputChar );
                                  else
                                       pout.write ( inputChar );
                             if ( pout != null )
                                  pout.flush ();
                                  pout.close ();
                             else
                                  System.out.flush();
                        catch ( Exception e ) { e.printStackTrace (); }     
              try
                   Runtime r = Runtime.getRuntime ();
                   Process p = r.exec ( command );
                   OutputMonitor out = new OutputMonitor ( p.getInputStream (), pipeout );
                   OutputMonitor err = new OutputMonitor ( p.getErrorStream (), pipeerr );
                   Thread t1 = new Thread ( out );
                   Thread t2 = new Thread ( err );
                   t1.start ();
                   t2.start ();
                   //p.waitFor ();
              catch ( Exception e ) { e.printStackTrace (); }
         public PipedInputStream getInputStream () throws IOException
              pipeout = new PipedOutputStream ();
              return new PipedInputStream ( pipeout );
         public PipedInputStream getErrorStream () throws IOException
              pipeerr = new PipedOutputStream ();
              return new PipedInputStream ( pipeerr );
         public void execInThread ()
              Thread t = new Thread ( this );
              t.start ();
         public static JPanel getContentPane ( JTextArea ta )
              JPanel p = new JPanel ( new BorderLayout () );
              JPanel bottom = new JPanel ( new FlowLayout () );
              JButton button = new JButton ( "Exit" );
              button.addActionListener ( new ActionListener ( )
                                       public void actionPerformed ( ActionEvent e )
                                            System.exit ( 0 );
              bottom.add ( button );
              p.add ( new JScrollPane ( ta ), BorderLayout.CENTER );
              p.add ( bottom, BorderLayout.SOUTH );
              p.setPreferredSize ( new Dimension ( 640,480 ) );
              return p;
         public static void main ( String[] argv )
              // --- Local class to run on the event dispatch thread to update the Swing GUI
              class GuiUpdate implements Runnable
                   private PipedInputStream pin;
                   private PipedInputStream perr;
                   private JTextArea outputArea;
                   GuiUpdate ( JTextArea textArea, PipedInputStream in )
                        pin = in;
                        outputArea = textArea;
                   public void run ()
                        try
                             // --- Reads whole file before displaying...takes too long
                             //outputArea.read ( new InputStreamReader ( pin ), null );
                             BufferedReader r = new BufferedReader ( new InputStreamReader ( pin ) );
                             String line;
                             for ( ;; )
                                  line = r.readLine ();
                                  if ( line == null ) { break; }
                                  outputArea.append ( line + "\n" );
                                  // outputArea.paint ( outputArea.getGraphics());
                        catch ( Exception e ) { e.printStackTrace (); }
              // --- Create and realize the GUI
              JFrame f = new JFrame ( "Output Capture" );
              f.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );
              JTextArea textOutput = new JTextArea ();
              f.getContentPane().add ( getContentPane ( textOutput ) );
              f.pack();
              f.show ();
              // --- Start the command and capture the output in the scrollable text area
              try
                   // --- Create the command and setup the pipes
                   SystemCommand s = new SystemCommand ( argv );
                   PipedInputStream stdout_pipe = s.getInputStream ();
                   PipedInputStream stderr_pipe = s.getErrorStream ();
                   // --- Launch
                   s.execInThread ( );
                   //s.exec ();
                   // --- Watch the results
                   SwingUtilities.invokeLater ( new GuiUpdate ( textOutput, stdout_pipe ) );
                   SwingUtilities.invokeLater ( new GuiUpdate ( textOutput, stderr_pipe ) );
                   //Thread t1 = new Thread ( new GuiUpdate ( textOutput, stdout_pipe ) );
                   //Thread t2 = new Thread ( new GuiUpdate ( textOutput, stderr_pipe ) );
                   //t1.start ();
                   //t2.start ();
              catch ( Exception e ) { e.printStackTrace (); }
              

    Thanks for pointing out the SwingWorker class. I didn't use it directly, but the documentation gave me some ideas that helped.
    Instead of using invokeLater on the long-running pipe-reader object, I run it on a normal thread and let it consume the output from the background thread that is running the system command. Inside the reader thread I create a tiny Runnable object for each line that is read from the pipe, and queue that object with invokeLater (), then yield() the reader thread.
    Seems like a lot of runnable objects, but it works ok.

  • Should I use a thread and (in this case) how?

    Hi:
    I have a Swing frame (frameA) and on which there is a button; if I double click it,
    it will bring up a second frame (frameB). On frameB, I will select a new button name
    from a combobox, and click "DONE" button, and frameB would change the name of the
    button on frameA to this new name I selected. And frameB would disappear as well.
    I am thinking of using another thread for painting frameB, because I don't know how long
    it would take for frameB to load up, and I don't want to block up the event-dispatching thread
    on frameA.
    However, since frameB uses another thread, and frameB also has an ActionListener
    associated with the DONE button, i am not sure how to make the thread stay alive
    so that it could check whether the ActionEvent is fired. So, in this case, is it necessary to use
    another thread to do the job? Or should I just use the same event-dispatching thread?
    Or is there another whole new approach much better?
    Thanks

    Quite simply, I wouldn't bother threading it.
    If you load, link and instantiate the pop-up frame (actually I'd use a Dialog here) before you trigger the pop-up, the reaction is more or less instant. The execution of th parent frame will continue after the pop-up has been made visible, so any way you cut it, you are going to get a brief pause in the parent UI while the pop-up is shown - you may as well have it when the button is clicked.
    Hope this helps.--
    <sig> http://www.itswalky.com http://www.crfh.net </sig>

Maybe you are looking for