This question already has answers here:
Java: for(;;) vs. while(true)
(9 answers)
Closed 1 year ago.
I have seen a weird version of the for loop where only (;;) is used to write something, for example:
for (;;) {
System.out.println("dabarkai");
}
My guess is that it behaves similarly like a while(true) loop. But if there are some diferences in their actions then your more than welcome to share them here.
It's an "infinite" loop, basically the same as while(true)
If you don't stop it manually (or by throwing Exception) it will run forever.
To stop it you can use return:
int i = 0;
for(;;) {
i++;
if(i == 10) {
return;
}
}
Related
This question already has answers here:
"loop:" in Java code. What is this, and why does it compile?
(12 answers)
Closed 4 years ago.
I was reading ThreadPoolExecutor's source code and saw the following code.
private boolean addWorker(Runnable firstTask, boolean core) {
retry:
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
// Check if queue empty only if necessary.
if (rs >= SHUTDOWN &&
! (rs == SHUTDOWN &&
firstTask == null &&
! workQueue.isEmpty()))
return false;
for (;;) {
int wc = workerCountOf(c);
if (wc >= CAPACITY ||
wc >= (core ? corePoolSize : maximumPoolSize))
return false;
if (compareAndIncrementWorkerCount(c))
break retry;
c = ctl.get(); // Re-read ctl
if (runStateOf(c) != rs)
continue retry;
// else CAS failed due to workerCount change; retry inner loop
}
}
Notice the retry word above. What does it do? I've never seen similar usages before. Is there a documentation about this syntax?
retry is not a keyword, but an identifier. It's a label. See the Java Language Specification for the break statement.
A break statement with label Identifier attempts to transfer control to the enclosing labeled statement (ยง14.7) that has the same Identifier as its label; this statement, which is called the break target, then immediately completes normally. In this case, the break target need not be a switch, while, do, or for statement.
Instead of breaking out of the innermost enclosing loop as it does by default, adding the identifier causes control to transer to the part of the code identified by this label.
In this case, when execution arrives at the break retry statement, it will go to a label retry: and continue from there.
This question already has answers here:
Why is i++ not atomic?
(10 answers)
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 4 years ago.
I wanted to test out multithreading for a project of mine, trying to also develop a solution in case something goes wrong.
So I made this small test:
main
public class main
{
static int addToCounter;
static int addToErrorCounter;
public static void main(String[] args) throws InterruptedException
{
int threads = 10;
Executor exec = new Executor();
for (int i = 0; i < threads; i++)
{
double error = Math.random();
testClass aldo = new testClass();
Thread thread = aldo.getThread(300, error);
exec.execute(thread);
}
while (threads != (addToCounter + addToErrorCounter))
{
System.out.println("Not all threads finished, number of finished threads is: " + (addToCounter + addToErrorCounter));
Thread.sleep(50);
}
System.out.println("Number of Threads that finished correctly: " + addToCounter);
}
}
testClass
import test1.main;
public class testClass
{
public Thread getThread(long time, double error)
{
Thread thread = new Thread()
{
public void run()
{
try
{
Thread.sleep(time);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
if (error > 0.5)
{
main.addToErrorCounter++;
throw new java.lang.Error("HELLO");
}
System.out.println("I DID THIS!");
main.addToCounter++;
}
};
return thread;
}
}
(you'll have to fix the imports, also I use a custom class Executor, although that's only a wrapper for ExecutorService)
The weird behaviour is that sometimes it works properly, and sometimes it doesn't (total terminated thread count is 9, although I can see clearly it printed "I DID THIS!" and the error exactly 10 times).
Any fix?
The Problem might be a racecondition.
the "++" operator is not atomic.
Imageine the following scenario. There are two Threads at the same time. both want to increase a number and finish.
The initial value of the number is 0.
Thread 0 reads the number, knows now it is 0.
Thread 1 reads the number, knows now it is 0.
Thread 0 (who knew it was 0) now writes 1 to the memory.
Thread 1 does not know, that the number has changed, and still believes the number is 0 so he also writes a 1 to the memory.
You need something like a synchronizing mechanisim, something like a lock, or a semaphore or something else.
have a look at this for more information: http://winterbe.com/posts/2015/04/30/java8-concurrency-tutorial-synchronized-locks-examples/
for your example you could use the "synchronized" example from that link.
add a method to your main class looking like this to increment the addToCounter and also to the addToErrorCounterto remove the effects from your error counter:
synchronized AddToError(int e){
addToError += e;
}
synchronized IncCounter(){
addToCounter++;
}
call those methods in your threads in the testclass instead of incrementing them unsynchronized.
My guess is that the postfix operator (main.addToCounter++) is not atomic. This line of code is probably equivalent to something like:
int temp = main.addToCounter;
main.addToCounter = temp + 1;
return temp;
With multiple threads doin this at the same time, two threads could obtain the same value for temp (because both peform the first line in the above pseudo-code before either performs the second), and hence the counter total will be too small once all threads are complete. See Why is i++ not atomic? for more information.
A quick fix in this situation is to make addToCounter an AtomicInteger, then use addToCounter.incrementAndGet() in place of addToCounter++.
This question already has answers here:
How to use conditional breakpoint in Eclipse?
(6 answers)
Closed 5 years ago.
Is it possible to have a condition on a breakpoint in Eclipse, and have the breakpoint "activate" after that condition has been met n times?
Say for example, in some sloppy mobile-written pseduocode, the breakpoint's condition is:
int n = 0;
If(i == j){
n++
If(n > 400)
true;
}
With i and j being values in my class.
To please the duplicate-hunt, note that I am not asking how to use a conditional statement, I am asking how I can count the number of times a breakpoint condition is met, then have the breakpoint stop my code. Hit does not do this, nor does using a condition in any way I can figure out.
To activate the breakpoint after the condition is met a certain number of times:
Open breakpoints dialog: Ctrl+double-click breakpoint
Check Conditional checkbox
Use following as condition:
if (i == j) {
int n = Integer.parseInt(System.getProperty("breakpoint.n", "0"));
n++;
System.setProperty("breakpoint.n", "" + n);
if (n > 400) return true;
}
return false;
This question already has answers here:
How to exit a while loop after a certain time?
(5 answers)
Closed 6 years ago.
I'm trying to do a script with PowerShell and I need to execute some Java code in a loop. So I do :
while(something){
java my_program
}
But my_program takes time and I would like to set a Timeout. How can I do this?
You could try something like this:
while($something){
$p = [diagnostics.process]::start("java my_program")
if ( ! $p.WaitForExit(1000) )
{
$p.kill()
}
}
I think this code will work fine for you, you can put while loop condition,
public class JavaTimeout {
public void myMethod(){
long startTime = System.currentTimeMillis(); // put the start time
while((System.currentTimeMillis() - startTime ) < 5000) // if if 5 second end
{
// your method do something here
}
System.out.println("5 sec end..."); // print the timeout
} // end myMethod method
} // end JavaTimeout Class
I hope that helps..
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What does for (;;) mean in Java?
I am reading some Java API docs, and I have encountered this loop of a very strange perky look, which elated me to come here and ask what is it about. Would be glad to find it as soon as possible. Thank you on your upcoming efforts.
public int read() throws IOException {
synchronized (lock) {
ensureOpen();
**for (;;)** {
if (nextChar >= nChars) {
fill();
if (nextChar >= nChars)
return -1;
}
if (skipLF) {
skipLF = false;
if (cb[nextChar] == '\n') {
nextChar++;
continue;
}
}
return cb[nextChar++];
}
}
}
for(;;)
That is an infinite loop.
For example, it's equivalent to something like
while(true)
Naturally, to exit such a loop, a branching statement is used.
EDIT: clearly the use of the word "infinite" was a bad choice. Still, for all intents and purposes, a for(;;) loop does not terminate using the same conditional mechanism of typical for loops. I believe this was the point of the question. The comments are just splitting hairs at this point.
for(;;)
This is an infinte loop, no variables initialization, no condition to check, no incremental step ... only exits the loop when execute the "return" sentence inside conditions.
Common for loop:
for(int i = 0 ; i < max ; i++)
Hope helps.
It means that the condition of termination of the cycle is not expressed in the usual form.
The only ways to terminate the cycle are the two return statements.
As stated by #Tom, this is an infinite loop.
Uses of this in your program could be if you would like to execute something forever.