Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing a Read-only Reference Between Threads

assume we have 2 threads, thread A and thread B.

thread A is the main method and contain large data structures.

is it possible to create a second thread and pass the address(a pointer) of the data structure (local to thread A) to thread B so both thread can read from the data structure?

the point of this is to avoid the need to duplicate the entire data structure on thread B or spend a lot of time pulling relevant information from the data structure for thread B to use

keep in mind that neither thread is modifying the data

like image 364
Jdak Avatar asked Dec 03 '25 19:12

Jdak


2 Answers

  1. In Java, the term pointer is not used, but reference.
  2. It is possible to pass it, as any other object, to another thread. As any (non-final) class in Java, you can extend it, add members, add constructors etc.
  3. (If you need to modify the data) You need to make sure that there are no concurrency issues.
like image 159
MByD Avatar answered Dec 05 '25 07:12

MByD


It's known as a reference in java, as you don't have access directly to a pointer in a conventional sense. (For most cases it's "safe" to think of it as every reference is a pointer that is always passed by value and the only legal operation is to dereference it. It is NOT the same as a C++ 'reference.')

You can certainly share references among threads. Anything that's on the heap can be seen and used by any thread that can get a reference to it. You can either put it in a static location, or set the value of a reference on your Runnable to point to the data.

public class SharedDataTest {

  private static class SomeWork implements Runnable {
    private Map<String, String> dataTable;

    public SomeWork(Map<String, String> dataTable) {
      this.dataTable = dataTable;
    }

    @Override
    public void run() {
      //do some stuff with dataTable
    }
  }

  public static void main(String[] args) {

    Map<String, String> dataTable = new ConcurrentHashMap<String, String>();

    Runnable work1 = new SomeWork(dataTable);
    Runnable work2 = new SomeWork(dataTable);

    new Thread(work1).start();
    new Thread(work2).start();

  }

}
like image 24
Affe Avatar answered Dec 05 '25 08:12

Affe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!