Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Many calls to static method in single thread

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

like image 449
Marcin Sanecki Avatar asked Dec 07 '22 13:12

Marcin Sanecki


2 Answers

System.err and System.out are two different streams which are interleaved in your console window - they're not necessarily synchronized. Try using System.*.flush() (nevermind, this doesn't seem to work) to force the output to be handled, or print all your output to the same stream.

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
like image 123
Jacob Raihle Avatar answered Dec 09 '22 03:12

Jacob Raihle


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

like image 32
Peter Lawrey Avatar answered Dec 09 '22 01:12

Peter Lawrey