Is usng while(true) loop in run mthd of thread good idea 2 make it wait ind

hi freinds.
sorry for writing short forms in my subject, but what i want to know is that is is using while(true) loop in run method of thread good idea to make it wait indefinately.
if not then what might be a good idea.
I Just need to Start a thread and make it wait indefinitely,
thanks

No. "while (true) {}" is a horribly bad way to do
nothing, as that thread will use 100% of the CPU.
What does "wait indefinitely" mean? Surely it can't
mean "wait forever", but if it doesn't mean that then
I can't guess what it does mean. Do you want to wait
until some condition is true? Or do you want to wait
a random amount of time? More information would help.Hello Dr.Clap, read your comments then checked my task manager and found that indeed it occupies 100% of CPU usage. thats really horrible , even i dont want that . ok i will explain u what i am trying to do along with my program on how i have accomplished it . please correct me where i went wrong.
My Requirement
my Application is deployed on JBOSS which has its JMS. now lets say i have defined a Queue named "MyAppQueue" and i know that all the senders whereever they may be will post there messages on this queue.
Now my responsibility is to write a MessageReceiver which is continously running and checking this queue for messages. whenever it receives a message it immidiately calls the messagesListener which processes the message.
So sow my requirement of Writing such MessageReceiver is that , it should always be in running mode(that means once i start it, it starts forever since this is going to be a REal time application) and continously checking the queue, as soon as some message comes it calls messageListener. and also that this messageReceiver should be fast , i mean coz many messages may come at once say 40-50 messages in a minute.
so please tell me how do i now write this MessageReceiver.
the way i have written
My Code
package test.jms;
import java.util.Properties;
import javax.jms.JMSException;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueReceiver;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class MyThreadReceiver implements Runnable{
    String queueName = null;
     Context jndiContext = null;
     QueueConnectionFactory queueConnectionFactory = null;
     QueueConnection queueConnection = null;
     QueueSession queueSession = null;
     Queue queue = null;
     QueueReceiver queueReceiver = null;
     TextMessage message = null;
     MyQueueListener myQueueListener = new MyQueueListener();
    /* (non-Javadoc)
     * @see java.lang.Runnable#run()
    String j;
    public void run() {
        // TODO Auto-generated method stub
        while(true){
           try {
           // Thread.sleep(10000);
        }catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
    public static void main(String[] args) {
        MyThreadReceiver myReceiver = new MyThreadReceiver();
        myReceiver.establishConnection();
      /* after connection is established to the queue, i am not closing the   connection.i am making a thread and passing my class object to it and in run method i have written while(true ) loop to somehow make my MessageReceiver program run indefinately.. */
        Thread thread = new Thread(myReceiver);
        thread.start();
        System.out.println("finished");
     this method opens connection to the queue. and i am not closing this connection .
    private void establishConnection(){
             queueName = "queue/testQueue";
                  try {
                    Properties env = new Properties();
                    env.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.NamingContextFactory");
                    jndiContext = new InitialContext();
               }catch (NamingException e) {
                    System.out.println("Could not create JNDI API " + "context: " + e.toString());
                    System.exit(1);
               try {
                    queueConnectionFactory = (QueueConnectionFactory)jndiContext.lookup("QueueConnectionFactory");
                    queue = (Queue) jndiContext.lookup(queueName);
               }catch (NamingException e) {
                    System.out.println("JNDI API lookup failed: " + e.toString());
                    System.exit(1);
               try {
                    queueConnection = queueConnectionFactory.createQueueConnection();
                    queueSession =      queueConnection.createQueueSession(false,Session.AUTO_ACKNOWLEDGE);
                    queueReceiver = queueSession.createReceiver(queue);
                    queueReceiver.setMessageListener(myQueueListener);
                    queueConnection.start();
               } catch (JMSException e) {
                    System.out.println("Exception occurred: " +
                    e.toString());
               } finally {
                    //if (queueConnection != null) {
                    //try {
                    //queueConnection.close();
                    //}catch (JMSException e) {}
   please correct my code. thanks in advance

Similar Messages

  • When you double click the circle buttom, and the little bar pops up from what you have been using... is it using data while being in there? is it a good idea to minimize evertthing out of there often so its not using more data ? or does it not matter?

    when you double click the circle buttom, and the little bar pops up from what you have been using... is it using data while being in there? is it a good idea to minimize evertthing out of there often so its not using more data ? or does it not matter?
    thanks!

    Not sure if it uses data, but that allows you to multitask.  To save battery life you should close out of all the apps.

  • Display a popup message while a loop is running

    Can somebody give me some good ideas on how I could create a popup that will appear when a loop is running and then disappear when the loop is finished. I would also like to show a status bar in the popup.

    Hi,
    I'd make a sub vi with a case in it. The case has three 'states': Show
    Window, Hide Window and NOP (no operation). The sub vi must be a dialog, but
    Show window when opend must be off.
    The Show Window and Hide Window case should have vi property nodes (no
    reference wired, to use it's own reference) with the 'show panel' property
    set to true and false. The NOP case is empty.
    Wire an enumerated to the case, and wire it's control to the connector pane.
    Also wire a status control to the connector pane.
    Put the sub vi before the while loop, with the Show Window option. The sub
    vi will show (perhaps you also want to initialise the status indicator in
    the Show Window case).
    In the loop, put the sub vi with the status control wired to the actual
    value, and NOP to
    the window control.
    When done (after the while loop, but be carefull about race conditions, )
    put the sub vi with Hide Window wired to it. (Put the enumerated inside the
    while loop and wire it through the while loop to the sub vi to prevent
    this.)
    Regards,
    Wiebe.
    "Terry S" wrote in message
    news:[email protected]..
    > Can somebody give me some good ideas on how I could create a popup
    > that will appear when a loop is running and then disappear when the
    > loop is finished. I would also like to show a status bar in the
    > popup.

  • I am using a timed while loop and am unable to get the loop to run at a speed of less than 1ms (I am currently using the Wait(ms) function). How can I get a faster response?

    I am trying to create a virtual engine within a timed while loop and am unable to get the loop to run at a speed of less than 1ms (I am currently using the Wait(ms) function). This does not however allow realistic engine speeds. How can I overcome this? I have access to a PCI-MIO-16E-4 board.

    andyt writes:
    > I am using a timed while loop and am unable to get the loop to run at
    > a speed of less than 1ms (I am currently using the Wait(ms) function).
    > How can I get a faster response?
    >
    > I am trying to create a virtual engine within a timed while loop and
    > am unable to get the loop to run at a speed of less than 1ms (I am
    > currently using the Wait(ms) function). This does not however allow
    > realistic engine speeds. How can I overcome this? I have access to
    > a PCI-MIO-16E-4 board.
    Andy,
    Unless you use a real time platform, getting extactly 1 ms loop rate
    (or even less) is impossible. It starts getting troublesome at about
    0.1 Hz for standard operating systems.
    I'd tackle your problem with "if i mod 10 == 0 then sleep 1 ms".
    Of
    course this is jerky by design.
    HTH,
    Johannes Nie?

  • Doesn't loop a while(true) !!!

    I made an Client Chat applet, but for some reason it doesn't do the read/write part to the socket that happens while(true)!!!
    Well, actually it doesn't even load the screen! I mean the layout...
    As you can see, wrote some System.out.println() to see where it gets stuck, and gets up to "7" and stops - it writes "7" only once and it's in a while(true)!!!
    Please help me...
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    import java.io.*;
    import java.net.*;
    public class main extends Applet {
      boolean sent = false;
      String senttxt = null;
      TextArea maintext = new TextArea(17,50);
      TextField sendtext = new TextField(40);
      Button send = new Button("Send!");
      public void init() {
        setLayout(new FlowLayout());
        add(maintext);
        add(sendtext);
        add(send);
        maintext.setEditable(false);
        cmain();
        catch(Exception e) {
          System.out.println(7);
      public main() {
      /**Construct the applet*/
      private void cmain() {
            Socket echoSocket = null;
            PrintWriter out = null;
            BufferedReader in = null;
            System.out.println(1);
            try {
                echoSocket = new Socket("127.0.0.1", 4445);
                  System.out.println(2);
                out = new PrintWriter(echoSocket.getOutputStream(), true);
                  System.out.println(3);
                in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
                  System.out.println(4);
            } catch (UnknownHostException e) {
                maintext.append("Couldn't find server - maybe offline");
                System.out.println("Couldn't find server - maybe offline");
            } catch (IOException e) {
                maintext.append("There was a problem connecting server");
                System.out.println("There was a problem connecting server");
              System.out.println(5);
            BufferedReader stdIn = new BufferedReader(new StringReader("User Connected!\n"));
              System.out.println(6);
            try {
              while (true) {
                System.out.println(7);
                  if(sent) {
                    stdIn = new BufferedReader(new StringReader(senttxt+"\n"));
                    try { out.println(stdIn.readLine()); } catch (IOException e) { }
                    senttxt = null;
                    sent=false;
                    System.out.println(8);
                  try { maintext.append(in.readLine()); } catch (IOException e) { System.out.println(9); }
            } finally {
              System.out.println(8);
              out.close();
              try { in.close(); } catch (IOException e) { }
              try { stdIn.close(); } catch (IOException e) { }
              try { echoSocket.close(); } catch (IOException e) { }
      public boolean action(Event evt, Object arg) {
        if(evt.target instanceof Button || evt.target instanceof TextField) {
          senttxt = sendtext.getText();
          sendtext.setText("");
          sent=true;
          return true;
        return false;
    }

    I gess your program stops waiting in the in.readLine() on the "try { maintext.append(in.readLine()); } catch (IOException e) { System.out.println(9); }" sentence.
    First time your program enters the while(true) it writes the "7", then goes directly to that sentence because sent==false. When reading something from in, it should write "7" again.

  • Disabling tabs while certain items are running

    Hello,
    In the following VI I am trying to get the "CAM" tab to be disabled and greyed out while the "ACQ Start" boolean is True and then become enabled again once the "ACQ Start" boolean becomes false.  I also want the "ACQ"  tab to do the same while the "Test" boolean is used.  Both boolean buttons will be controlling functions that are using the same camera interface, only not at the same time, but I want to make sure I don't go from the active "ACQ" tab which is in the process of acquiring images to the "CAM" tab to test my camera settings while the camera interface is already being used by the "ACQ" tab functions.  The VI I attached is a scaled down version of the main VI I'm developing, but hopefuly it has enough to give someone an idea of what I'm trying to accomplish.  I've searched around and came up with the event structure that's in the VI.  What I have disables the "CAM" tab when I press the "ACQ Start" button, but it doesn't become enabled once again after I stop the acquisition.
    Any ideas?
    Thanks!
    Solved!
    Go to Solution.
    Attachments:
    Tab Disabling.vi ‏150 KB

    It will become enabled again if you set the front panel controls for the "Page index" and the "Page Enabled State" correctly before you press those buttons. Why do these two controls even exist in the first place? Your code should handle accessing the correct tab and then setting the enabled/disabled state based on the value of the Boolean.
    Other comments:
    Your architecture is dubious. Is the loop in case 0 supposed to be running until some condition? Right now it only runs once. 
    You do not need to perform all those gymnastics in getting the tab that's active. Just wire the tab terminal directly to the case structure selector. The datatype of the tab is essentially an enum, so the case items are automatically updated.
    What is the purpose of OR'ing a Boolean control with a False constant? Is that False constant a placeholder for something else? Otherwise, it's pointless. 
    The Wait function in the outer loop doesn't do you any good. The event structure will prevent the outer loop from going to the next iteration until an event is generated that the event structure is set up to handle.
    You may want to consider looking at a more robust programming architecture such as the Producer-Consumer architecture.

  • How to stop a "continue if true loop" inside a "stop if true loop"?

    Hello guys, I have "continue if true loop" that I want to stop when I press the stop button of the surrounding "stop if true loop".
    Notice that I ran through all of this to keep the push button released and keep the LED lit.
    However, when I press the stop button nothing happens, so:
    1) How can I overcome that?
    2) Are the shift registers even necessary?
    (Please fix my VI)
    T. A.
    Attachments:
    prob.vi ‏7 KB

    Your code makes no sense. Why don't you study it with execution highlighting while operating the controls.
    What is the purpose of the shift registers? none! Delete them. Why did you place them?
    If you want LabVIEW to react to a button, the control terminal should be in the innermost loop. Currently, the code cannot escape from the innermost loop, because the value of the termination condition cannot change. It will spin millions of times per second doing nothing useful.
    There are many ways to keep an LED lit after a latch action switch, e.g. with an event structure. (see attached. Make sure to stop the VI with the stop button, else the LED remains lit.). Of course the code is pretty dumb, because you can never turn the LED off again while the VI is running.
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    probMOD.vi ‏8 KB

  • Alternative Solution to While(true) in MessageQueue

    Hey Guys
    Ive decided to decouple my system so it will hold a queue of messages that can then by passed on to Observers.
    I used a while(true) statement that would constantly loop to get updates and then notify observers.
    That was the only way I could think of doing it, is there a better solution?
    This is an idea of whats happening so far:
    public class MessageQueue extends Observable implement Observer, Runnable
           //Array stores messages
           String[] message;
           //this checks my array for new messages and removes and returns the first message from the array
           public String get()
           //this places items on the array
           public void put(String message)
           public void run
                   while(true)
                          String msg = get();
                          setChanged();
                          notifyObservers(msg);
    }Is there a better method that wont take up alot of CPU usage?
    any help on this would be great
    Cheers

    Hey took your advice and opted to use a Vector so i could add and test if it was empty:
        public synchronized String get()
            String  s = null;
            while(!message.isEmpty())
                s = message.firstElement();
                message.removeElement(s);
                try
                    wait();
                catch(InterruptedException ex)
                    ex.printStackTrace();
            return s;
        }Message was edited by:
    FatClient

  • While(true) VS for(;;)

    I usually use for(;;) if I need to make a loop run until it hits a "break;". Is Java more comfortable with having a while(true) instead? The reason I ask, is because it just came to me, that for(;;) might be doing more operations than while(true), since it would check for what would normally be in the (;;)...not sure though, so I came here for advice.
    Obviously its probably not a big optimization, but advice would be useful for future coding.
    Thank you.
    -Neo-

    BTW I always prefer to have an expression in the
    while loop...
    But then, it's not an "infinite" loop... :o)Disagree: in this case, while(true) is also NOT
    an infinite loop.
    Because: both can be interrupted!Disagree on the basis of pedantry and semanticism. LOL
    Conceded that they can be interrupted (I hesitate to write "duh"); however, notice the quotes around "infinite". In the common usage I've seen, while(someExpression()) or while(someBooleanPrimitive) are intended to be interrupted (e.g., the condition will likely change at some point), while while(true) is intended to run "infinitely".
    Maybe after I have a few more years of experience, I'll notice a different trend, but my experience so far is what I based my light-hearted comment on.

  • Error in sql query as "loop has run more times than expected (Loop Counter went negative)"

    Hello,
    When I run the query as below
    DECLARE @LoopCount int
    SET @LoopCount = (SELECT Count(*) FROM KC_PaymentTransactionIDConversion with (nolock) Where KC_Transaction_ID is NULL and TransactionYear is NOT NULL)
    WHILE (
        SELECT Count(*)
        FROM KC_PaymentTransactionIDConversion with (nolock)
        Where KC_Transaction_ID is NULL
        and TransactionYear is NOT NULL
    ) > 0
    BEGIN
        IF @LoopCount < 0
            RAISERROR ('Issue with data in KC_PaymentTransactionIDConversion, loop has run more times than expected (Loop Counter went negative).', -- Message text.
                   16, -- Severity.
                   1 -- State.
    SET @LoopCount = @LoopCount - 1
    end
    I am getting error as "loop has run more times than expected (Loop Counter went negative)"
    Could any one help on this issue ASAP.
    Thanks ,
    Vinay

    Hi Vinay,
    According to your code above, the error message make sense. Because once the value returned by “SELECT Count(*)  FROM KC_PaymentTransactionIDConversion with (nolock) Where KC_Transaction_ID is NULL and TransactionYear is NOT NULL” is bigger than 0,
    then decrease @LoopCount. Without changing the table data, the returned value always bigger than 0, always decrease @LoopCount until it's negative and raise the error.
    To fix this issue with the current information, we should make the following modification:
    Change the code
    WHILE (
    SELECT Count(*)
    FROM KC_PaymentTransactionIDConversion with (nolock)
    Where KC_Transaction_ID is NULL
    and TransactionYear is NOT NULL
    ) > 0
    To
    WHILE @LoopCount > 0
    Besides, since the current query is senseless, please modify the query based on your requirement.
    If there are any other questions, please feel free to ask.
    Thanks,
    Katherine Xiong
    Katherine Xiong
    TechNet Community Support

  • To exit from the while(1) loop

    Hi all ,
    I have a simple question that if in a callback function of a command button, i use a While(bLoop)
    loop , where bLoop is a boolean variable initially set to TRUE, then how can i break or exit from this while Loop by using a control on the front panel  , which exits the while loop by setting     bLoop = FALSE .
    I have tried it but it is not exiting  
    Solved!
    Go to Solution.

    The problem here is that CVI normally only executes one callback at a time. While you are in one control callback, no GUI processing and subsequent calls to other callbacks normally occurs.
    You can try the following approach - but it is not really the best method:
        while (b_loop) {              // Inside a callback
            ...                       // Perform your tight program loop
            ProcessSystemEvents ();   // Force CVI to see if any GUI controls need servicing
    If you have a different control callback to clear the global b_loop, this quick-and-dirty approach might work for you.
    You should only use this technique for very simple programs - it can rapidly spiral out of control and end up in a mess if you're not careful. NI recommends that you do not use ProcessSystemEvents() inside a control callback.
    JR

  • While having a perfectly running iTunes and all programs associated, I was notified of the iTunes 10.4 upgrade. After following typical directions, I have had nothing but trouble. First "iTunesHelper was not installed correctly. Please reinstall iTunes. E

    While having a perfectly running iTunes and all programs associated, I was notified of the iTunes 10.4 upgrade. After following typical directions, I have had nothing but trouble. First “iTunesHelper was not installed correctly. Please reinstall iTunes. Error 7 (Windows error 5)” occurred. Following directions found at https://discussions.apple.com/message/15087646#15087646, I now get the following “iTunes.exe - System Error The program can't start because AVFoundationCF.dll is still missing from your computer. Try reinstalling the program to fix this problem.”, Along with “iTunesHelper was not installed correctly. Please reinstall iTunes. Error 7 (Windows error 126)” I am running Win 7 Ultimate 64 bit on HP TouchSmart tx2-1275dx. I was one week away from buying an iPad but not if this is what I have to deal with. Please help

    I actually managed to resolve this on my own by downloading iTunes from the Apple website and reinstalling iTunes that way. Here's the link: http://www.apple.com/itunes/download/ That should fix your problem. Good luck!

  • System Error 998 While loading the Labview Run-Time Engine

    Hello.
    I have a DLL made with LV 7.1 I run the dll using a C compiler and works great in WINXP, but cannot run in Win2K. Error is:
    "System error 998 while loading the Labview Run-Time Engin(c:\program
    files\National Instruments\Shared\Labview Run-Time\7.1\\lvrt.dll)
    READVOLTAGE requires a version 7.1 (or compatible) Labview Runtime
    Engine. Please contact the vendor of READVOLTAGE to correct this
    problem"
    READVOLTAGE is my function inside the dll. The runtime is already
    installed. I tried it in another WINXP running machine and works fine.

    This is actually a Microsoft bug with statically loaded DLLs. There are a couple of workarounds for it, and I have included two links below to posts that address this issue:
    Not found error message from LabVIEW runtime when called from VC++ with statically linked MFC
    I get error 998 when calling a LabVIEW buildt DLL from MSVC++
    Kind Regards,
    E. Sulzer
    Applications Engineer
    National Instruments

  • An unexpected error occurred while the job was running. (ID 104 Details: The parameter is incorrect (0x80070057))

    We are using DPM Version: 4.1.3465.0 with System Center 2012 Service Pack 1 to back up VMs in our Hyper V Cluster. We have a total of 37 VMs with a combination of 2008r2 servers and 2012 servers. One of our 2012 servers will not backup, and we consistently
    get the message "An unexpected error occurred while the job was running. (ID 104 Details: The parameter is incorrect (0x80070057))". I have seen this error message when I Googled it, but cannot get past it. I have deleted the Protection Group and
    data and tried to re-create, but get the same errors. I also thought the the server might be mis-reporting the data size, but I expanded that to cover the replication data. I have also tried to perform consistancy checks multiple times with no luck. I have
    not seen a difinitive answer from my Google searches, so was hopeful someone has seen this also, and have had success in resolving. Currently this server has no backup recovery points, so I am worried if it does crash. I think I have the rollups installed
    as well.

    Hi Kelly,
    does the issue still persists?

  • Does anyone know of a VI or how to go about writing one that will prevent the computers time/date from being disabled while an application is running.

    Does anyone know of a VI or how to go about writing one that will prevent the computers clock/time from being disabled while an application is running. The time and date can normally be reset while an application is running by clicking on the time/date in the lower right-hand corner of the computer screen. I have an application that runs over several days and it is critical that the time and date of the computer not be changed. Is there an easy way to lock this out from the user? Note that I am what I consider an advanced beginner in LV.
    Thank you,
    Chuck
    Solved!
    Go to Solution.

    That is not something you can do from LabVIEW, as it is an operating system operation, and it will depend on the operating system that you're using. On Windows you can use a group policy to control this. Please Google on "prevent time and date change in windows".
    Also, please try to refrain from stuffing your entire message in the subject block. Keep the subject short, but descriptive enough so it can be understood what you are basically asking. Thanks.

Maybe you are looking for

  • Mac Pro has slowed to a crawl - Please Help Me!

    Hello, For some time now my Wireless or Wired Internet connection using my Mac Pro has slowed to almost nothing. For example, This page took 5 mins to load and now Internet use has become unusable. I feel its my Mac Pro because all other Apple Comput

  • JNI and security

    Hi, We are coding new functionallity on a legacy C code. We are using JNI to to comunicate to an opensource library. We faced with the need to create some files and to connect to a remote host, but due to the jvm sandbox we cannot operate as we need.

  • Special characters in phone number

    Hi, My company decided that all private calls should be made with the prefix *140# in the phone number, allowing seperation in the bill. First I added this prefix to the phone numbers of all my private contacts in the Address Book, but when i perform

  • Cannot set ringtone!!

    I have had my Palm Pro for a while now, this is my second one actually and my first one had the same problem.  How exactly do you change your incoming call ringtone?  I put my ringtones in the My Ringtones folder.  I long select and choose "set as ri

  • Support;   Anyone know how to get .mac support on the phone?

    It appears the only way to get help concerning a .mac issue is by emailing them and waiting 24 hours or trying this discussion board. Anyone know of way to call them? Thanks