3

I'm stymied- can someone suggest how I can correctly pass a TreeMap (or similar collection) parameter to a thread. Using a named class, I can pass a String parameter no problem, but after much experimentation can't get TreeMap to work - it always has zero length. Obviously a String is very different from a TreeMap but still there should be some way to make it work.

The program is a background service that gets data from various sensors - I need to do some data processing, save to sd card etc. on a separate thread. I've read numerous posts such as Runnable with a parameter? and various duplicates without finding any solutions.

// String version works fine
public class MyThread implements Runnable {
        private String s;
        public MyThread(String s) {
            this.s = s;
        }
        public void run() {
        // works great, can process s data, save to sd card, etc.
        }
}
//called by
String s = "mylongcsvstring";
Runnable r = new MyThread(s);
new Thread(r).start();

//TreeMap version doesn't work
public class MyThread implements Runnable {
    private TreeMap<Long, SomeObject> t;
    public MyThread(TreeMap<Long, SomeObject> t) {
        this.t = t;
    }
    public void run() {
    // need to process t but size is zero
    }
}

//called by
TreeMap<Long, SomeObject> tm = new TreeMap<>();
tm.put(Long,SomeObject); // up to a few hundred objects
Runnable r = new MyThread(tm);
new Thread(r).start();
tkreyche
  • 31
  • 2
  • Is there any chance the map is altered by another thread? You could try `Collections.unmodifiableMap` or `synchronizedMap`. – nasch Jul 06 '17 at 18:40
  • No there is no other thread modifying the map - I'll run a test with your suggestions tonight...thanks, Tom – tkreyche Jul 06 '17 at 19:30
  • Interesting. The code should really work, starting a thread should make a happens-before relationship. I guess you should localize the problem. Maybe you could write a main method and log the size with System.out.println and invoke it as a normal java program. And then include it all in your question. – Ruslan Jul 19 '17 at 22:47

0 Answers0