Fix memory leak and optimize device monitoring.