Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use shared memory on Java threads?

I am implementing a multi-threaded program in Java, where each thread is of a type class Node extends Thread.

All these classes generate certain values which will be used by other classes.

For main it's easy to get the values from the generated threads, but from within threads itself, how can I get the values on other threads?

//Start the threads from a list of objects
for (int i = 0; i < lnode.size(); i++) { 
    lnode.get(i).start();
}

thanks

like image 606
Luis S Avatar asked Dec 12 '12 00:12

Luis S


2 Answers

If you do something like:

class MyThreadRunnable implements Runnable {
    List<String> strings;

    MyThreadRunnable(List<String> strings) {
        this.strings = strings;
    }

    public void run() {
        strings.add(getName());
    }
}

// ...

List<String> sharedStrings = new ArrayList<String>();
Thread t1 = new Thread(new MyThreadRunnable(sharedStrings));
Thread t2 = new Thread(new MyThreadRunnable(sharedStrings));

t1.start();
t2.start();

then both t1 and t2 (two different threads of the same type) will be using the same list, and see changes to it made from the other thread.

Actually, since I'm not using any synchronisation for brevity, it's also possible this would corrupt the list in some unpredictable way and cause weird errors. I strongly encourage you investigate process synchronisation, and the java.util.concurrent package when working with concurrency.

like image 145
millimoose Avatar answered Sep 22 '22 06:09

millimoose


If are threads of the same process/jvc instance you will not need "shared memory", you only need a reference for your data inside your treads, for example via constructor or static reference. But you will need a synchronization / control access mechanism if more than one thread writes on that data.

like image 30
nms Avatar answered Sep 21 '22 06:09

nms