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 ) );
    }
}

2 Answers 2

0

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

Sign up to request clarification or add additional context in comments.

5 Comments

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
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 !
that was helpfull, Thanks
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: baeldung.com/java-8-streams-introduction
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.