This easy code eats system memory and kill VM - is there a way to protect against such memory leaks?

you can set a max_heap_size per process: