3 Replies Latest reply: Jan 7, 2004 3:18 PM by 807582 RSS

    problem with the run method of a thread

    807582
      Hello,

      I want to create a listener, which inform me when a object was delete by the gc. so I wrote the code you see below.

      New I have the problem: in the run method of the thread i use a while block, and this block will never ending, but if a add a system.out in the block everything works fine. Got anybody a sulotion or a idea where the proplem is ?


      package de.akull.reflect;



      //import de.akull.reflect.exception.ReflectException;



      import java.lang.ref.*;

      import java.util.Map;

      import java.util.HashMap;



      public class ObjectLoader {



      /** Contains all singleton object references; the key is the class name. */

      private static Map objects = new HashMap();



      /**

      * A simple Helper.

      */

      private static class ListenerThread extends Thread {



      private ReferenceQueue q = null;



      private WeakReference ref = null;



      private String className = null;



      public ListenerThread(Object obj) {



      q = new ReferenceQueue();



      ref = new WeakReference(obj, q);



      className = obj.getClass().getName();



      // saves the reference in the object map.

      objects.put(className, ref);

      }



      /**

      * Returns the reference to the Object.

      *

      * @return - the reference to the object.

      */

      public Reference getReference() {

      return ref;

      }



      /**

      * Method run.

      */

      public void run() {



      while( q.poll() == null) {



      // the problem. if there is no system.out the while block

      // will never ending



      System.out.println("d");

      }



      ref.clear(); //removes the refernece.



      objects.remove(className);

      }

      }



      /**

      * Loads a class via reflection.

      *

      * @param className - name of the class.

      * @return - the inctance of the class.

      * //@throws ReflectException - construction failed.

      */

      public static Object load(String className) /*throws ReflectException*/ {



      Object obj = null;



      /* simple implementation for tests */

      obj = new String("Hello");



      ListenerThread run = new ListenerThread(obj);



      run.start();



      /*if( objects.containsKey(className) ) {

      obj = ((Reference) objects.get(className)).get();

      } else {



      obj = ReflectHelper.createObject(className, new Object[]{"hallo"});



      ListenerThread run = new ListenerThread(obj);



      run.start();

      } */



      return obj;

      }



      public static void main(String args[]) /*throws ReflectException*/ {



      Object obj = load(String.class.getName());



      try {

      Thread.sleep(1000);

      } catch(InterruptedException e) {

      e.printStackTrace();

      }



      obj = null;

      }

      }