Sunday, September 21, 2025

Capital Date Mistake

 This article was originally pusblished on JRoller on April 10, 2014

Here is a small piece of code. Can you tell what it prints?

  SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd");
  Calendar cal = Calendar.getInstance();
  cal.set(Calendar.YEAR, 2014);
  cal.set(Calendar.MONTH, Calendar.DECEMBER);
  cal.set(Calendar.DAY_OF_MONTH, 31);
  Date d = cal.getTime();
  System.out.println(sdf.format(d));

If you naively answered "2014-12-31", then I would tell you just this: you are really naive.

If you run this code under Java 6, you will get back an IllegalArgumentException, with the message "Illegal pattern character 'Y'". Now it might hit you that, indeed, the character for Year in a DateFormat is the lower case 'y'.

However, this code runs under Java 7, because the capital 'Y' was added to the DateFormat. But it does not stant for Year, but for Week Year. If, like me, you do not know what a Week Year is, here is the JavaDoc explanation:

A week year is in sync with a WEEK_OF_YEAR cycle. All weeks between the first and last weeks (inclusive) have the same week year value. Therefore, the first and last days of a week year may have different calendar year values.
For example, January 1, 1998 is a Thursday. If getFirstDayOfWeek() is MONDAY and getMinimalDaysInFirstWeek() is 4 (ISO 8601 standard compatible setting), then week 1 of 1998 starts on December 29, 1997, and ends on January 4, 1998. The week year is 1998 for the last three days of calendar year 1997. If, however, getFirstDayOfWeek() is SUNDAY, then week 1 of 1998 starts on January 4, 1998, and ends on January 10, 1998; the first three days of 1998 then are part of week 53 of 1997 and their week year is 1997.

In short, my exemple code will print "2015-12-31", because the last days of the year belong to a week of the following year.

Why don't I know my disk is full?

This article was originally posted on JRoller on March 14, 2014

We had this interesting problem lately, that an application had a corrupted file after a disk got full. The strange thing was that the app did not know that the disk was full. We were expecting an IOException, but no trace of it nowhere. Moreover, the app went on running, and resumed writing in the file when someone deleted a big file from the disk.

While looking on the net for how to know when a disk is full, we got this code strip on StackOverflow:

  FileOutputStream fos = ...;
  fos.write("hello".getBytes());
  fos.getFD().sync();
  fos.close();

This forces the OS to force synchronization of the file with its internal buffer, and throws a SyncFailedException when the disk is full. However, this has horrible performance. So we kept looking for our IOException. After a bit of investigation, we found out the culprit: PrintWriter.

The PrintWriter class can be very useful, since it wraps common print methods around a stream. Also, it automatically creates a BufferedWriter, as you can see in this constructor:

    public PrintWriter(File file) throws FileNotFoundException {
        this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))),
             false);
    }

Another features of the PrintWriter, and now we get to the problem, is that most of its methods do not throw any Exception. Here is an example of a typical PrintWriter method:

    public void write(char buf[], int off, int len) {
        try {
            synchronized (lock) {
                ensureOpen();
                out.write(buf, off, len);
            } 
        } 
        catch (InterruptedIOException x) {
            Thread.currentThread().interrupt();
        }
        catch (IOException x) {
            trouble = true;
        } 
    } 

You can see that all IOExceptions are caught, and a boolean is set to true. The only way to know that something went wrong is to call the method checkError(). This only tells you that something went amiss, but not what, since you lost the exception.

    public boolean checkError() {
        if (out != null) {
            flush();
        } 
        if (out instanceof java.io.PrintWriter) {
            PrintWriter pw = (PrintWriter) out;
            return pw.checkError();
        }  else if (psOut != null) {
            return psOut.checkError();
        } 
        return trouble;
    } 

Notice how it checks if it wraps another PrintWriter or a PrintOutputStream, because it knows that they swallow the Exception.

At the end, we replaced the PrintWriter with a simple FileWriter, because we did not need the PrintWriter in our case. We only needed a Writer to give to our CSV exporter library, which already wrapped it in a BufferedWriter. Now, IOExceptions are nicely bubbling up, and we know when our disk is full. 

AutoCloseable when not available

 This article was originally posted on JRoller on January 14, 2014

On his blog, Brian Oxley shows a neat way in JDK 8 to use non AutoCloseable object having a close-like method in a try with resources construct, using the new method references. For those of us who are still stuck with JDK 7 for some time, here is the (uglier) equivalent code:


	final Foo foo = new Foo();
	try (AutoCloseable ignore = new AutoCloseable() {
		@Override
		public void close() {
			foo.close();
		} 
	}) {
		foo.doFoo();
	} 

Permutations and Combinations

 This article was originally posted on JRoller on October 22, 2013

A simple piece of code for calculating all permutations of a given word:

    public static List permutations(String s) {
        List list = new ArrayList<>();
        permutations(list, s, "");
        return list;
    }

    private static void permutations(List list, String from, String to) {
        if (from.isEmpty()) {
            list.add(to);
        }
        else {
            for (int i = 0; i < from.length(); i++) {
                permutations(list,
                        new StringBuilder(from).deleteCharAt(i).toString(),
                        to + from.charAt(i));
            }
        }
    }

The code for permutations of N elements out of a word is a simple modification of the previous program:

    public static List permutationsN(String s, int n) {
        List list = new ArrayList<>();
        permutationsN(list, s, "", n);
        return list;
    }

    private static void permutationsN(List list, String from, String to, int n) {
        if (to.length() == n) {
            list.add(to);
        }
        else {
            for (int i = 0; i < from.length(); i++) {
                permutationsN(list,
                        new StringBuilder(from).deleteCharAt(i).toString(),
                        to + from.charAt(i),
                        n);
            }
        }
    }

For Combinations, that is when order is not important, another small modification does the trick:

    public static List combination(String s, int n) {
        List list = new ArrayList<>();
        combination(list, s, "", 0, n);
        return list;
    }

    private static void combination(List list, String from, String to, int index, int n) {
        if (to.length() == n) {
            list.add(to);
        }
        else {
            for (int i = index; i < from.length(); i++) {
                combination(list,
                        new StringBuilder(from).deleteCharAt(i).toString(),
                        to + from.charAt(i),
                        i,
                        n);
            }
        }
    }

Modal vs Always on Top

This article was originally posted on JRoller on Auguts 2, 2013

Here is an interesting piece of code:

      public static void main(String[] args) throws Exception {
          JFrame alwaysOnTopFrame = new JFrame(\"Always on top Frame\");
          alwaysOnTopFrame.setAlwaysOnTop(true);
          alwaysOnTopFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
          alwaysOnTopFrame.setSize(500, 500);
          alwaysOnTopFrame.setVisible(true);
          alwaysOnTopFrame.setLocationRelativeTo(null);

          JOptionPane.showConfirmDialog(null, \"coucou\");
      }

It displays a simple frame, with the "Always on Top" activated, then opens a modal dialog. What will happen? Which one will prevail and be in front of the other?

As it turns out, if you try to run this code, you will see the Frame hiding the modal dialog box, although the application waits for you to answer the dialog first. What will appear to the average user is that there is a frozen window which does not react to anything. Impossible to move it or close it, until you guess that there is a dialog box behind it.

Of course, if you know it, you can discard the dialog box using Enter or Escape key, or the Alt+F4 combination, or access the dialog box menu through Alt+Space and move it around using the arrow keys. But the average user won't know it.

What is the solution? There is actually an option that you can set on the Frame, so that it will still respond to user actions even though there are modal dialogs on the screen. It is called Modal Exclusion Type. Try adding the following line:

  alwaysOnTopFrame.setModalExclusionType(ModalExclusionType.APPLICATION_EXCLUDE);

When is a SwingWorker really done?

This article was originally posted on JRoller on April 25, 2013

Imagine you have a SwingWorker running, and you would like to know if it has terminated its job. You notice that it has a isDone() method, and say to yourself: "great! I can use it!". But are you sure you know what it is really doing? Are you sure that all your work will be over when it returns 'true'? You would say: "of course, it is called isDone". Well, let's have a closer look.

When you create a SwingWorker, it creates a Callable, and wraps it in a Future:

        Callable callable =
                new Callable() {
                    public T call() throws Exception {
                        setState(StateValue.STARTED);
                        return doInBackground();
                    }
                };

        future = new FutureTask(callable) {
                       @Override
                       protected void done() {
                           doneEDT();
                           setState(StateValue.DONE);
                       }
                   };

The Future will be executed by a ThreadPool (of maximum 10 threads). The doInBakground() is called, returning a value that will be used by the Future for its set() method. From this point onwards, calling the isDone() method will yield true. And this is even before the Future's done() method is called. So isDone() only means that doInBackground() terminated. Not what I was thinking.

OK, so why not use the getState() method. I see clearly that it is called by the Future right after the call to doneEDT(). But let's have a look at the doneEDT() method:

    private void doneEDT() {
        Runnable doDone =
            new Runnable() {
                public void run() {
                    done();
                }
            };
        if (SwingUtilities.isEventDispatchThread()) {
            doDone.run();
        } else {
            doSubmit.add(doDone);
        }
    }

As you can see, if we are already in the EDT, we execute immediately the method. But we know that we are started from a ThreadPool, so this is not the case. The doSubmit, surprisingly, uses a Timer and schedules the task in 30ms. Not a SwingUtilities.invokeLater() as I expected, but the result is the same: the getState() will return DONE before we even start the done() method. The PropertyChange are notifying you of the state change. So basically, you are left to yourself.