1

i have a big json file that contains a long List of informations, and i need to read-only the list in many sub-threads.
in java we can pass variables by value only and not by reference, i would like to keep my program as light as possible on memory/disk usage .
for now i pass the full list or only it's sub-lists to every thread i create.
is there a way to access the same List variable from all the threads without copying the full List into each thread ?
i need 'ONLY TO READ' the list

here is how my program works

1 - service ( wait for file creation )
2 - read the created Json file content into MyList
3 - start threads on parts of MyList with different limits/offsets

what i'm trying to do is somthing like this

List<Map<String,String>> MyList = JsonToObject(filePath);
executor = Executors.newFixedThreadPool( 10 );

in the Luncher class

List<Map<String,String>> MyList = JsonToObject(filePath);
executor = Executors.newFixedThreadPool( 10 );
int limit = 10;
int offset= 0;
for ( int i = 0 ; i < MyList.size() && offset <  MyList.size() ; i++ ) {
    offset = i * 10 ;
    Child thread = new Child( limit , offset );
    executor.submit( thread );
}

in the Child class

public void run(){
    for ( int i = this.offset ; i < this.limit ; i++ ) {
        this.doSomthingWith ( Luncher.Mylist.get( i ) );
    }
}
zakaria35
  • 857
  • 1
  • 7
  • 12

2 Answers2

0

The reference to the list is passed by value, so just pass the list into whatever method you are using in your thread.

PaulNUK
  • 4,774
  • 2
  • 30
  • 58
  • won't doing this make my programe use too much memory ? because i wil have a copy of MyList in the main programe and in evry sub-thread – zakaria35 Jan 24 '18 at 11:59
  • you said _The reference to the list is passed by value _ , i thought _ passing by value _ in java means it copys all the value content in the new variable in the called function not only the reference to the value. could you clarify this for me please ! – zakaria35 Jan 24 '18 at 12:31
  • See here: https://stackoverflow.com/questions/11397008/does-a-list-object-get-passed-by-reference – PaulNUK Jan 24 '18 at 12:39
  • 1
    that was helpfull, Thanks – zakaria35 Jan 24 '18 at 12:42
  • By the way, if you want to process parts of a list asynchronously, have a look at using parallel streams rather than manually coding with threads: http://www.baeldung.com/java-8-streams-introduction – PaulNUK Jan 24 '18 at 13:50
0

is there a way to access the same List variable from all the threads without copying the full List into each thread?

yes, there is. Moreover, there is no way to copy list or any other complex data structure into thread - because the thread's memory contains only stack of procedure call frames, where local variables of primitive types and references reside. Any complex data structures reside in the heap memory, equally accessible to all the threads in the same process.

Alexei Kaigorodov
  • 13,189
  • 1
  • 21
  • 38