UF.MAIL

当尝试使用已被释放的资源时,就会报告 UF(使用已释放)问题。UF.MAIL 警告表明尝试使用已关闭的 Java Mail API 对象。

示例 1

复制
 public Collection<Message> getMessages(final Session session,
                                    final String... folderNames) throws MessagingException {
 final Collection<Message> result = new ArrayList<Message>();
 Store store = session.getStore("pop3");
 store.connect();
 
 for (String folderName : folderNames) {
     Folder folder = getFolder(store, folderName);
     if (folder != null) {
         Message messages[] = folder.getMessages();
         for (int i = 0, n = messages.length; i < n; i++) {
             result.add(messages[i]);
         }
     }
 }
 
 return result;
 }
 
 private Folder getFolder(Store store, final String folderName) throws MessagingException {
 if (folderName == null) {
     return null;
 }
 
 try {
     Folder folder = store.getFolder(folderName);
     folder.open(Folder.READ_ONLY);
     return folder;
 } catch (MessagingException e) {
     store.close();
 }
 return null;
 }

针对第 20 行的代码段报告 UF.MAIL:如果在第 38 行引发 MessagingException,则 Java Mail API 对象 store 将被方法 getFolder() 关闭。这将导致出现问题,因为在循环的下一次迭代中,将再次调用方法“getFolder()”,而它将尝试访问已被关闭的存储。

示例 2

复制
 public Collection<Message> getMessages(final Session session,
                                        final String... folderNames) throws MessagingException {
     final Collection<Message> result = new ArrayList<Message>();
     Store store = session.getStore("pop3");
     store.connect();
 
     for (String folderName : folderNames) {
         Folder folder = getFolder(store, folderName);
         if (folder != null) {
             Message messages[] = folder.getMessages();
             for (int i = 0, n = messages.length; i < n; i++) {
                 result.add(messages[i]);
             }
         }
     }
 
     return result;
 }
 
 private Folder getFolder(Store store, final String folderName) throws MessagingException {
     if (folderName == null) {
         return null;
     }
 
     try {
         Folder folder = store.getFolder(folderName);
         folder.open(Folder.READ_ONLY);
         return folder;
     } catch (MessagingException e) {
         store.close();
         throw e;
     }
 }

来自之前部分的代码段经过了修复。方法 getFolder() 现在会再次引发 MessagingExcpetion。