Many calls to static method in single thread
-
21-06-2021 - |
Question
please look at this class, static method calls and output.
public class OneThreadManyStaticCalls {
public static final Calculator calculator = new Calculator();
public static void main(String[] args) {
dummy(0, 1, 1);
dummy(0, 2, 2);
dummy(0, 3, 5);
dummy(0, 4, 44);
dummy(0, 5, 5);
}
public static void dummy(int a, int b, int expected) {
System.out.print(System.currentTimeMillis() + "\t");
if (calculator.add(a, b) == expected) {
System.out.println("OK");
} else {
System.err.println("NOK");
}
}
}
I got diffrent (order from System.out.print) ouputs running this program. Example:
NOK
NOK
1342527389506 OK
1342527389506 OK
1342527389506 1342527389506 1342527389506 OK
Could any of you explain me (with details) why? Thanks in advance. sznury
Solution
System.err and System.out are two different streams which are interleaved in your console window - they're not necessarily synchronized. Try using (nevermind, this doesn't seem to work) to force the output to be handled, or print all your output to the same stream.System.*.flush()
public static void dummy(int a, int b, int expected) {
System.out.print(System.currentTimeMillis() + "\t");
if ((a + b) == expected) { // I don't have your Calculator :<
System.out.println("OK");
} else {
System.out.println("NOK");
}
}
Gives this result
1342528255764 OK
1342528255764 OK
1342528255764 NOK
1342528255764 NOK
1342528255764 OK
OTHER TIPS
A simpler example is
for (int i = 0; i <= 20; i++)
(i % 2 == 0 ? System.out : System.err).println(i);
There is NO guarantee of order between two streams even if they both go to the console.
prints on one run (changes with each run)
1
0
3
2
5
4
7
6
9
8
11
10
13
12
15
14
17
16
19
18
20
Note: In my IDE the System.err lines appear in red
@Jacob Raihle is correct to show that this is the case change your system.err call to a system.out
public static void dummy(int a, int b, int expected) {
System.out.print(a+" "+b+" = "+expected);
if((a+b)==expected)
System.out.println(" OK");
else
System.out.println(" NOK");
}