Nirmesh
Nirmesh

Reputation: 305

Running while loop infinitely without any code inside in java

Lets say I have written a infinite write loop but didn't have statement inside it? Will it create any issue like memory will be full etc or JVM will stop responding after sometime?

Upvotes: 1

Views: 187

Answers (3)

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147154

You'll certainly keep one hardware thread busy. It wont create any objects, so memory isn't a direct issue as such.

However, the context is important.

  • If it is a high priority thread, the system may become unresponsive. This is implementation specific. Twenty years ago I wrote an infinite loop that made a Windows NT system unresponsive. (I think this was a TCP proxy and only happened when an IBM 3090 running CICS sent an empty keep alive frame to a 3270 terminal. Good times.)
  • If the thread is holding any locks, that wont be released.
  • If the thread does something useful, that useful thing wont happen. For instance if you were to write the loop in a finaliser (and the system only has one finaliser thread), no other object will get finalised and therefore not garbage collected either. The application may behave peculiarly. It'salways fun to run random code on the finaliser thread.

Upvotes: 0

Bsquare ℬℬ
Bsquare ℬℬ

Reputation: 4487

Why would you do something like that?

To answer, it wouldn't consume endless memory but Cpu usage could be a pain with really no instruction at all.

At minimum, you should help CPU preemption allowing the Thread to yield:

Thread.yield();

You can read this in Java Api Javadoc:

A hint to the scheduler that the current thread is willing to yield its current use of a processor. The scheduler is free to ignore this hint.

Yield is a heuristic attempt to improve relative progression between threads that would otherwise over-utilise a CPU. Its use should be combined with detailed profiling and benchmarking to ensure that it actually has the desired effect.

It is rarely appropriate to use this method. It may be useful for debugging or testing purposes, where it may help to reproduce bugs due to race conditions. It may also be useful when designing concurrency control constructs such as the ones in the java.util.concurrent.locks package.

Upvotes: 1

Karol Dowbecki
Karol Dowbecki

Reputation: 44952

An infinite loop might and probably will result in 100% CPU core utilization. Depending what you mean by "write loop" a similar technique is called Busy Waiting or Spinning.

spinning as a time delay technique often produces unpredictable or even inconsistent results unless code is implemented to determine how quickly the processor can execute a "do nothing" loop, or the looping code explicitly checks a real-time clock

Upvotes: 0

Related Questions