Uploaded image for project: 'Commons Codec'
  1. Commons Codec
  2. CODEC-96

Base64 encode() method is no longer thread-safe, breaking clients using it as a shared BinaryEncoder

    XMLWordPrintableJSON

Details

    • Bug
    • Status: Closed
    • Major
    • Resolution: Fixed
    • 1.4
    • 1.7
    • None

    Description

      Streaming support was added to Base64 in commons-codec 1.4 with CODEC-69. This introduced instance variables to Base64 which means the class can no longer be used as a shared BinaryEncoder instance.

      For example, BinaryEncoder has an interface which could be (and was) used like this with Base64:

      class Example {
          private BinaryEncoder encoder = new Base64();
      
          byte[] someMethod(byte[] data) {
              try {
                  return encoder.encode(data);
              }
              catch (EncoderException e) {
                  throw new RuntimeException(e);
              }
          } 
      }
      

      Base64 is no longer thread-safe in commons-codec 1.4, so code like the above which is accessed by multiple threads can throw NullPointerException:

      java.lang.NullPointerException
      	at org.apache.commons.codec.binary.Base64.encode(Base64.java:469)
      	at org.apache.commons.codec.binary.Base64.encode(Base64.java:937)
      	at ... (application code)
      

      Looking at the implementation of Base64, I think making it thread-safe for this kind of usage would be quite tricky. I haven't attempted to prepare a patch.

      I would be happy if it was indicated in the Javadoc that Base64 is not thread-safe and should not be shared. However, some other users of commons-codec might be more worried about this regression.

      Attachments

        1. CODEX-96-2.patch
          46 kB
          Sebb
        2. codec-96-3rd-attempt.patch
          5 kB
          Julius Davies
        3. CODEC-96.patch
          44 kB
          Sebb

        Issue Links

          Activity

            People

              Unassigned Unassigned
              mjryall Matt Ryall
              Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

              Dates

                Created:
                Updated:
                Resolved: