简体   繁体   中英

How to preserve and object instantiated in a thread

Supposing I have the following

public class Foo {
   private Map<Integer,SomeObject> myMap;
   public Foo() {
      this.myMap = new HashMap<Integer,SomeObject>();
   }

   private class Runner implements Runnable {
       public void run() {
            SomeObject someObj = new SomeObject();
            Foo.this.myMap.put(10,someObj);
            //'soObj' will always be null upon retrieval later...
       }   
   }
}

If I create a thread with a Runnable of type 'Runner' and start the thread, it will run. In the run method, I simply create an instance of 'SomeObject' and place it in the map of the outer class. However, when I attempt to get a value from 'myMap' later on, the 'SomeObject' instance will always be null. I can't understand why as I have placed a reference into the map 'myMap' which still lives on in the heap after the thread finishes. Is there a way around this?!

Thanks very much

If you are writing from one Thread and reading from another, you'll have to think about concurrenct access and visibility. As your code-snipplet does not show any sign of that, I guess that might be the problem. In any case you have to fix it first, before digging deeper into the problem.

You'll have to do some sort of synchronization like synchronized-blocks , read-write-locks or special concurrent classes like ConcurrentHashMap . Make sure you get yourself familiar with those techniques, especially a ConcurrentHashMap can be tricky to handle depending on how you want to use it.

Edit: For a simple synchronized Map you might use synchronizedMap() from the great Collections-class, but be careful with iterations on those Maps (see the corresponding javadoc for details).

It could be a problem with the way your objects are instantiated. It should be:

    Foo foo = new Foo();
    Thread thread = new Thread(foo.new Runner());
    thread.start();

Maybe you should look at the FutureTask in java.util.concurrent - it can return an object.

http://download.oracle.com/javase/6/docs/api/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM