concurrency - Java: Protecting an object from being accessed by multiple threads -


i have opengl es 2.0 app. within it, have class contains array of type of object (this simplified question):

public class storelist(){  thislist storeitems[];      public storelist(int nuberofitems){          thislist = storeitems[numberofitems];      }  } 

initially, populate list , @ points during app (when user in 'store' scene), it's possible new items added list, so, example, list this:

before              after inserting object 'fish' index 1  index 0  - dog      index 0 - dog index 1  - fox      index 1 - fish index 2  - bird     index 2 - fox index 3  - snake    index 3 - bird                     index 4 - snake 

now, list iterated through various reasons. example, rendering, updating positions etc.

the problem have that, app uses 2 threads - gl rendering thread, , main/ui thread.

when user performs action, ui thread calls 'insertobject' method inserts item detailed above. rendering thread happily doing it's thing , if rendering object @ index 1 @ same time 'insertobject' called, starts cause problems (each object in list has different number of opengl quads draw , number draw contained in variable in object itself), if original object @ index 1 had 5 quads, , new object has 4, starts attempt draw 5th quad , manner of issues (index out of bounds example).

the render method, updatelogic method , ontouchevent methods declared synchronized, i'm still getting issue.

i'm not sure how go ensuring object (the instance of storelist , within , it's 'thislist' array) can updated 1 thread @ time.

the questions i've seen relating concurrency issues have been protecting method being called multiple threads , not objects, i'm little confused.

would appreciate guidance.

why not use synchronized block on storeitems instead of synchronizing insert/update methods. synchronized block guarantee 1 thread may execute insert code block, or other code block(say update) synchronized on same object (i.e. storeitems) @ time.


Comments