Please tell me how to cope with a memory leak or more to solve the problem.
Once a second, I get the values from the database that need to be processed. The resulting data array is processed in separate threads so as not to slow down the process:
public class MyThread extends Thread{ @Override public void run(){ Map<Integer, MyObject> ar = new HashMap(); while(true){ //запрос к базе while(resultSet.next()){ ar.put(resultSet.getInt(1),new MyObject()); } if(!ar.isEmpty(){ WeakReference<MyHandler> ex = new WeakReference<MyHandler>(new MyHandler(ar)); ex.get().start(); ar.clear(); } //затем обновляю строки в базе по массиву, что бы сделать следующую выборку } }} public class MyHandler extends Thread{ Map<Integer, MyObject> ar; public MyHandler(Map<Integer, MyObject> ar){ this.ar = new HashMap<>(ar); } @Override public void run(){ //обработка массива }} So I have a memory leak, how can I implement it differently? A lot of threads are created, I don’t know how they release memory at the end.
Thank you in advance!
Threadis gc-root, i.e. as long as the stream is alive, objects referenced in the stack cannot be collected. But ifMyHandlercompleted, then the map with all its contents should be collected.WeakReferencefor a local variable, in my opinion, is not needed. - zRrrOutOfMemoryError, run jvm with the-XX:+HeapDumpOnOutOfMemoryErrorkey-XX:+HeapDumpOnOutOfMemoryError, and analyze the resulting heap dump in Eclipse MAT or its counterparts, there you will see which objects are in memory. You can also connectjvisualvm(included in jdk) to the running program and see - zRrr