FileSystem uses a WeakHashMap to store it's open file handles

This means if lua code forgets to free a handle, the java GC will still
be able to collect the stream (andclose the file in the finaliser in the
process)
This commit is contained in:
Daniel Ratcliffe 2017-05-05 00:52:26 +01:00
parent 42f2235d45
commit 09215daa03
1 changed files with 8 additions and 11 deletions

View File

@ -11,6 +11,7 @@
import dan200.computercraft.api.filesystem.IWritableMount;
import java.io.*;
import java.lang.ref.WeakReference;
import java.util.*;
import java.util.regex.Pattern;
@ -291,7 +292,7 @@ private String toLocal( String path )
}
private final Map<String, MountWrapper> m_mounts = new HashMap<String, MountWrapper>();
private final Set<IMountedFile> m_openFiles = new HashSet<IMountedFile>();
private final WeakHashMap<IMountedFile, Object> m_openFiles = new WeakHashMap<IMountedFile, Object>();
public FileSystem( String rootLabel, IMount rootMount ) throws FileSystemException
{
@ -308,18 +309,15 @@ public void unload()
// Close all dangling open files
synchronized( m_openFiles )
{
while( m_openFiles.size() > 0 )
for(IMountedFile file : m_openFiles.keySet())
{
IMountedFile file = m_openFiles.iterator().next();
try
{
try {
file.close();
}
catch( IOException e )
{
m_openFiles.remove( file );
} catch (IOException e) {
// Ignore
}
}
m_openFiles.clear();
}
}
@ -669,7 +667,7 @@ private synchronized <T extends IMountedFile> T openFile(T file, Closeable handl
throw new FileSystemException("Too many files already open");
}
m_openFiles.add( file );
m_openFiles.put( file, null );
return file;
}
}
@ -679,7 +677,6 @@ private synchronized void closeFile( IMountedFile file, Closeable handle ) throw
synchronized( m_openFiles )
{
m_openFiles.remove( file );
if( handle != null )
{
handle.close();