_gc.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #
  2. # Copyright 2019 The FATE Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import typing
  17. from collections import deque
  18. from fate_arch.abc import GarbageCollectionABC
  19. from fate_arch.common.log import getLogger
  20. LOGGER = getLogger()
  21. class IterationGC(GarbageCollectionABC):
  22. def __init__(self, capacity=2):
  23. self._ashcan: deque[typing.List[typing.Tuple[typing.Any, str, dict]]] = deque()
  24. self._last_tag: typing.Optional[str] = None
  25. self._capacity = capacity
  26. self._enable = True
  27. def add_gc_action(self, tag: str, obj, method, args_dict):
  28. if self._last_tag == tag:
  29. self._ashcan[-1].append((obj, method, args_dict))
  30. else:
  31. self._ashcan.append([(obj, method, args_dict)])
  32. self._last_tag = tag
  33. def disable(self):
  34. self._enable = False
  35. def set_capacity(self, capacity):
  36. self._capacity = capacity
  37. def gc(self):
  38. if not self._enable:
  39. return
  40. if len(self._ashcan) <= self._capacity:
  41. return
  42. self._safe_gc_call(self._ashcan.popleft())
  43. def clean(self):
  44. while self._ashcan:
  45. self._safe_gc_call(self._ashcan.pop())
  46. @staticmethod
  47. def _safe_gc_call(actions: typing.List[typing.Tuple[typing.Any, str, dict]]):
  48. for obj, method, args_dict in actions:
  49. try:
  50. LOGGER.debug(f"[CLEAN]deleting {obj}, {method}, {args_dict}")
  51. getattr(obj, method)(**args_dict)
  52. except Exception as e:
  53. LOGGER.debug(f"[CLEAN]this could be ignore {e}")