0

How anyone can write an Indefinite running Thread without a costly loop like while?

Like I don't want something like this

public void run() {

            while(true)
            {
                do Blah Blah Blah
                Thread.sleep(.....);

            }

        }

Any optimized way to write such a long running thread.

Thanks in advance.

Aryan
  • 1,767
  • 2
  • 22
  • 39

3 Answers3

6

I find while (true) { ... } to be the cleanest way of implementing a plain infinite loop. I don't think there is any more compact or cost efficient way of doing it.

Some people prefer for (;;) { ... } though, but I think it looks awkward.

In terms of cost, javac compiles both as

public static void main(java.lang.String[]);
  Code:
   0:  ...
       ...
       ...
       goto 0

}

and if you indeed want the loop to be infinite, I can't see any more efficient way of doing it.


Since you have a Thread.sleep in your code, I would also recommend you to look into for instance java.util.Timer and java.util.TimerTask.


If your loop tries to do something repeatedly, you are right that you're probably wasting CPU time in the long run. Especially if you happen to have many instances of this type of thread. In this case I would recommend you to look into the observer pattern. Let the object waiting for something, listen to the objects affecting the possibility of succeeding with what it's trying.

aioobe
  • 413,195
  • 112
  • 811
  • 826
1

In what way do you consider while(true) "costly"? Do you have any evidence that this is affecting your performance? What operation would you consider to be cheaper than it?

Note that from your comment:

I guess such a infinite while loop blocks your CPU. Isn't dat? So I consider it costly.

it sounds like you're considering the whole loop, not the while part. So let's look at what you're doing in the loop:

do Blah Blah Blah
Thread.sleep(.....);

You're explicitly telling the thread to sleep. While it's sleeping, it won't be consuming CPU resources. So no, it's not costly. Admittedly if your sleep period is very short and your "do Blah Blah Blah" is very quickly, you'll be looping an awful lot - but in that case you should consider increasing the sleep time. (You should also consider other approaches which allow you to signal to the thread that you wish it to quit cleanly, and do so even while it's sleeping, without having to interrupt the thread.)

You haven't given us any information about what you're really trying to achieve, but fundamentally the use of while isn't a problem here. Just think about how often you want to loop, and whether it's really a simple time-based value. For example, if this thread is meant to process work, then perhaps you want a producer/consumer queue of some description - there's no need for the thread to sleep while it has work to do, but there's no need for it to wake up until there's work to do. That's only an example, of course - without more information we really can't give much more advice.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Yes I added sleep so that I can free the CPU. What I wanted to ask really is that Is there any more intelligent way to do the same. – Aryan May 18 '12 at 06:15
  • 1
    @Aryan: If you want to run the same thing again and again, a loop is ideal. As I say at the end of my answer, we can't really give you much advice without knowing more context. Please give us the bigger picture and we may be able to suggest alternatives. We haven't even got a *hint* as to what the body of the loop is doing, given that you've only told us "do blah blah blah". Please read http://tinyurl.com/so-hints – Jon Skeet May 18 '12 at 06:16
  • Actually I have a client trying to get some configurations from a server. If a server is down it fails and goes in sleep state. Starting a server is manual step. So I am not sure when it will happen a minute or day. So I was searching for most efficient solution – Aryan May 18 '12 at 06:26
  • @Aryan, it sounds like you would be better off with some observer. (Added this to my answer.) – aioobe May 18 '12 at 06:44
  • The problem having Observer implementation is there is no other way of communication between server and client. And these two separate entities interact with each other this way only. – Aryan May 18 '12 at 07:01
  • @Aryan: It sounds like the problem isn't really in loop efficiency - it's a problem of you balancing the cost of making lots of successful calls with the cost of letting the server be down for longer than you want. Only you know that balance - but it's got nothing to do with the *implementation* efficiency of the loop. – Jon Skeet May 18 '12 at 07:12
  • @Aryan It's still hard for me to be sure, but is this a task that is required per client? If you have numerous clients which can be connected at any single time, then you should definitely consider the issue I outlined. Otherwise, your concern for efficiency just comes down to the "blah blah blah" that Jon Skeet was talking about. – Nadir Muzaffar May 18 '12 at 07:35
1

Since we're guessing what you've defined as cost, I thought I'd let you know of a possible cost that I can think of.

A thread usually has some stack memory associated with it. The amount of stack memory associated with a thread for many applications, such as desktop/user applications, isn't really an issue. But say you're developing a server that has to handle a long term connection from each of it's numerous users. And lets say that for every connected user, the server has to perform the same task repetitively (like what you might be doing in your while loop). Addressing this solution with a thread per connection/user can become quite costly. So instead of blocking/sleeping on the thread, it can often be more efficient to ask a thread from a ThreadPool to do the same task whenever you get the event to do so. This can drastically improve memory usage. I think such a optimization could be considered whenever you can have lots of threads relative to the amount of memory available.

Probably not the case for you since you said "indefinite", but it was an interesting problem that I came across recently so I thought I'd blab about it.

Nadir Muzaffar
  • 4,772
  • 2
  • 32
  • 48