Friday 22 April 2016

multithreading - java : accessing parent variable in multi threaded programe



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> MyList = JsonToObject(filePath);
executor = Executors.newFixedThreadPool( 10 );


in the Luncher class



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

Answer



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


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...