MappedByteBuffer的umap() JAVA Bug!

来源:互联网 发布:淘宝写文案范文 编辑:程序博客网 时间:2024/04/28 00:56

 用到NIO的相关类--MappedByteBuffer时的一个BUG。
例如:

 

public void testMappedByteBufferRead() {
    
int length = 10485760;
    MappedByteBuffer out 
= null;
    RandomAccessFile ranFile 
= null;
    File file 
= null;
    
try {
        file 
= new File("d:/test.txt");
        ranFile 
= new RandomAccessFile(file, "rw");
        out 
= ranFile.getChannel().map(
        FileChannel.MapMode.READ_WRITE, 
0, length);
        
for (int i = 0; i < length; i++)
            out.put((
byte'x');
        System.out.println(
"Finished writing");
    } 
catch (FileNotFoundException e) {
        e.printStackTrace();
    } 
catch (IOException e) {
        e.printStackTrace();
    }
    
try {
        file.delete();
        System.out.println(
"Delete File");
                                Thread.sleep(
100000);
    } 
catch (Exception e) {
        e.printStackTrace();
    }
}

上面的操作都会正常的完成,除了最后一步:文件无法删除!即使你通过资源管理器直接强制删除也不行,说"文件正在使用",也就是说out无法关闭!

在网上收集一些资料都说是JAVA的一个BUG,一些网友自己写out的close()函数:
public static void clean(final Object buffer) throws Exception {
       AccessController.doPrivileged(
new PrivilegedAction() {
    
public Object run() {
            
try {
        Method getCleanerMethod 
= buffer.getClass()
                                .getMethod(
"cleaner"new Class[0]);
                   getCleanerMethod.setAccessible(
true);
                   sun.misc.Cleaner cleaner 
= (sun.misc.Cleaner) 
                               getCleanerMethod.invoke(buffer, 
new Object[0]);
                   cleaner.clean();
              } 
catch (Exception e) {
                 e.printStackTrace();
             }
                     
return null;
      }
         });
}
但调用此函数后依然无法删除文件,即out没有关闭。 
此问题比较棘手,不知各位技术牛人是否有更好的方法,望赐教,谢谢。
原创粉丝点击