Skip to content

Commit

Permalink
Better release bioformats resources.
Browse files Browse the repository at this point in the history
Before this change, from the repl, issuing commands like:
```
import large_image
ts = large_image.getTileSource('/some/bioformats/file')
```
and then exiting would hang because the local reference to the tile
source would still contain a reference to the unclosed bioformats
resource.
  • Loading branch information
manthey committed Dec 16, 2020
1 parent 1e02eed commit 3189dd5
Showing 1 changed file with 18 additions and 4 deletions.
22 changes: 18 additions & 4 deletions sources/bioformats/large_image_source_bioformats/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@
import math
import numpy
import os
import six
import threading
import types

Expand All @@ -54,11 +53,25 @@


_javabridgeStarted = None
_openImages = []


def _monitor_thread():
main_thread = threading.main_thread()
main_thread.join()
if len(_openImages):
try:
javabridge.attach()
while len(_openImages):
source = _openImages.pop()
try:
source._bioimage.close()
except Exception:
pass
source._bioimage = None
finally:
if javabridge.get_env():
javabridge.detach()
_stopJavabridge()


Expand Down Expand Up @@ -91,8 +104,7 @@ def _stopJavabridge(*args, **kwargs):
_javabridgeStarted = None


@six.add_metaclass(LruCacheMetaclass)
class BioformatsFileTileSource(FileTileSource):
class BioformatsFileTileSource(FileTileSource, metaclass=LruCacheMetaclass):
"""
Provides tile access to via Bioformats.
"""
Expand Down Expand Up @@ -150,6 +162,7 @@ def __init__(self, path, **kwargs): # noqa
except AttributeError as exc:
self._logger.debug('File cannot be opened via Bioformats. (%r)' % exc)
raise TileSourceException('File cannot be opened via Bioformats. (%r)' % exc)
_openImages.append(self)

rdr = self._bioimage.rdr
# Bind additional functions not done by bioformats module.
Expand Down Expand Up @@ -245,6 +258,7 @@ def __del__(self):
try:
javabridge.attach()
self._bioimage.close()
_openImages.remove(self)
finally:
if javabridge.get_env():
javabridge.detach()
Expand All @@ -265,7 +279,7 @@ def _getSeriesStarts(self, rdr):
frameList = []
nextSeriesNum = 0
try:
for key, value in six.iteritems(seriesMetadata):
for key, value in seriesMetadata.items():
frameNum = int(value)
seriesNum = int(key.split('Series ')[1].split('|')[0]) - 1
if seriesNum >= 0 and seriesNum < self._metadata['seriesCount']:
Expand Down

0 comments on commit 3189dd5

Please sign in to comment.