@@ -72,13 +72,26 @@ public class Tracer implements Runnable {
7272 final static int LOG_QUEUE_SIZE = 1024 * 1024 ;
7373 final static int BUFFER_SIZE = 10 * 1024 * 1024 ;
7474 final static int MAX_TIME_BETWEEN_FLUSHES = 1000 ;
75+ final static Object FLUSH = new Object ();
7576
7677 private static class AsyncLogger extends Thread {
7778 final PrintStream ps ;
7879 final BlockingQueue <Object > queue = new ArrayBlockingQueue <Object >(LOG_QUEUE_SIZE , true );
7980 AsyncLogger (PrintStream ps ){
8081 this .ps = new PrintStream (new BufferedOutputStream (ps , BUFFER_SIZE ), false );
81- start ();
82+ start ();
83+
84+ new Thread (){
85+ @ Override public void run (){
86+ while (true ){
87+ try {
88+ Thread .sleep (MAX_TIME_BETWEEN_FLUSHES );
89+ queue .add (FLUSH );
90+ } catch (InterruptedException e ) { }
91+ }
92+
93+ }
94+ }.start ();
8295 }
8396
8497 void printMessage (Object message ){
@@ -91,23 +104,12 @@ void printMessage(Object message){
91104 }
92105 }
93106
94- long lastFlush = System .currentTimeMillis ();
95- void maybeFlush (){
96- long now = System .currentTimeMillis ();
97- if (now - lastFlush > MAX_TIME_BETWEEN_FLUSHES ){
98- ps .flush ();
99- lastFlush = now ;
100- }
101- }
102-
103107 @ Override public void run (){
104108 try {
105109 while (true ){
106- maybeFlush ();
107- Object message = queue .poll (50 , TimeUnit .MILLISECONDS );
108- if (message != null ) printMessage (message );
109- else ps .flush ();
110-
110+ Object message = queue .take ();
111+ if (message == FLUSH ) ps .flush ();
112+ else printMessage (message );
111113 }
112114 } catch (InterruptedException interrupt ){
113115 }
0 commit comments