Improve code generics and removes resource leaks