Its a small challange made by me, I wanna see how fast people can figure out whats missing in order to make this code work properly, good luck
What the code does is printing how many loops were made after 10 seconds basically.
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class Test
{
private int a;
private long b;
private ScheduledThreadPoolExecutor c = new ScheduledThreadPoolExecutor(1);
public Test()
{
c.scheduleAtFixedRate(new RunnableWrapper(), 0, 1000, TimeUnit.MILLISECONDS);
while (a < 10)
b++;
System.out.println("Loops: " + b);
}
private class RunnableWrapper implements Runnable
{
@Override
public void run()
{
a++;
}
}
public static void main(String[] args)
{
new Test();
}
}
It does, but the problem with the code is that the script never finishes (infinite loop)
Why? Reading âscheduleAtFixedRateâ I thought it would schedule that function to be run every 1 seconds, so after 10 seconds a would be 10? And the while loop would be exited?
Why? Reading âscheduleAtFixedRateâ I thought it would schedule that function to be run every 1 seconds, so after 10 seconds a would be 10? And the while loop would be exited?
Hereâs a real challenge. Make a Java class that inherits from multiple classes. I mean a real class that inherited all methods from 2 different class. Iâve actually did this for fun during presentation⌠it was fun to see java developers reaction when I showed a live demo. If youâre curious then look up AOP Mixin or introduction⌠some crazy stuff that youâll never use in real project.
why do you claim that this challange is weird? have you even tried getting it solved? so far I got no solutions and in fact this is something developers should know.
But why doesnât it exit? Is it a scope problem? The value of a is changed in RunnableWrapper, but this canât be seen in Test() ?
Not excactly a scope problem, if youâll print a inside the loop the code will work properly and youâll see the value increases as it should.
a small hint:
The problem comes when a is not involved anywhere within the while statement, so basically the compiler âthinksâ that a will never reach 10 and it changes the statement to the following:
while (true)
b++;
making the code never end.
Thereâs a special keyword that needs to be added to prevent this, nuff hints
Well since there hasnât been an answer for a while ill say it
To make the compiler aware of changes done in such situations on a variable the volatile keyword needs to be added on var a.
this tells the compiler that the var might be changed from outside of its class so its not automatically turns it to true
Iâve googled to find the solution, but all I could find was sites that explain that if the value isnât changed in the loop itself, it defaults the while criteria to true. Iâd say thatâs something that should be pointed out when explaining while loops?