Русский English Tags View Sergey Zolotaryov's profile on LinkedIn Sign-in
Reporting progress from Java applications in console
Permanent link 19-12-2018 anydoby java

Just needed to report progress in a form of a progress bar in a console app (I tend to be writing these a lot nowadays since I joined a data science team). So here's the trick to report progress:


    public class Progress implements AutoCloseable {

        private final double maxValue;
        private final AtomicLong value = new AtomicLong();
        private volatile int prevPercentage;

        public Progress(double maxValue) {
            this.maxValue = maxValue;
        }

        public void tick() {
            final long t = value.incrementAndGet();
            final double percentage = (int) (t / maxValue * 100);
            if (prevPercentage != (int) percentage) {
                synchronized (this) {
                    if (prevPercentage != percentage) {
                        prevPercentage = (int) percentage;
                        updateProgress(percentage / 100);
                    }
                }
            }
        }

        public static Progress ofMax(double maxValue) {
            return new Progress(maxValue);
        }

        static void updateProgress(double progressPercentage) {
            final int width = 50; // progress bar width in chars

            System.out.print("\r[");
            int i = 0;
            for (; i < (int) (progressPercentage * width); i++) {
                System.out.print(".");
            }
            for (; i < width; i++) {
                System.out.print(" ");
            }
            System.out.print("]");
        }

        @Override
        public void close() {
            System.out.println();
        }
    }

and here's a sample of usage:


        String ss[] = new String[10000];
        try (Progress progress = Progress.ofMax(ss.length)){
            for (String string : ss) {
                // process this string
                progress.tick();
            }
        }

Have fun progressing...

Add a comment

Previous article Unit testing Google Storage code