Gradle print vs println


(Andrii) #1

I understand the difference between print and println methods.
But why Gradle with default logging level prints output with println but doesn’t with print or printf?

TaskProgress.groovy

public class TaskProgress {

    private static final String PROGRESS_SYMBOLS = '_/\\_';
    private static final int MAX_POINTS = PROGRESS_SYMBOLS.length() - 2

    AtomicBoolean inProgress = new AtomicBoolean(true)
    int currentChar = 0
    int delta = 1

    private TaskProgress() {}

    static TaskProgress doProgress() {
        Log.error("START PROGRESS")
        def taskProgress = new TaskProgress();
        taskProgress.startProgress()
        return taskProgress
    }

    private void startProgress() {
        Thread.start {
            Log.error('STARTING:')
            while (inProgress.get()) {
                if (currentChar > MAX_POINTS) {
                    delta = -1
                } else if (currentChar == 0) {
                    delta = 1
                }
                println PROGRESS_SYMBOLS[currentChar] // it works
                print PROGRESS_SYMBOLS[currentChar] // it doesn't work
                currentChar += delta
                if (!inProgress.get()) break;
            }
            Log.error('STOPPING:')
        }
    }

    public void stopProgress() {
        Log.error("STOP PROGRESS")
        inProgress.set(false)
    }

}

buid.gradle

task progress {
    doLast {
        def progress = TaskProgress.doProgress()
        Thread.sleep(1000)
        progress.stopProgress()
    }
}

Or even simplier example:

task example1 {
    doLast {
        Thread.start {
            print 10
        }
    }
}

task example2 {
    doLast {
        Thread.start {
            println 20
        }
    }
}

Just call ./gradlew example1 example2 and see that output is:

:example1
:example2
20

When I use print in the main thread it works okay. Is it a defect?


(Thomas Hirsch) #2

I am not sure what causes this behaviour, but I could make your example work by calling

System.out.flush()

after the call to print.