简体   繁体   中英

Java: Protecting an object from being accessed by multiple threads

I have an OpenGL ES 2.0 App. Within it, I have a class which contains a array of another type of object like so (this is simplified for the question):

public class StoreList(){

thisList StoreItems[];

    public StoreList(int nuberOfItems){

        thisList = StoreItems[numberOfItems];

    }

}

Initially, I populate the list and then at certain points during the app (when the user is in the 'store' scene), it's possible for new items to be added into the list, so, for example, the list could look something like this:

Before              After inserting object 'Fish' into 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, this list is iterated through for various reasons. For example, for rendering, for updating their positions etc.

The problem I have is that, my app uses 2 threads - The GL Rendering thread, and the Main/UI thread.

When the user performs a certain action, the UI thread calls an 'insertObject' method which inserts an extra item as detailed above. However the rendering thread is happily doing it's thing and if it was rendering the object at index 1 at the same time 'insertObject' was called, then it starts to cause problems (each object in the list has a different number of openGL quads to draw and the number to draw is contained in a variable in the object itself), so if the original object at index 1 had 5 quads, and the new object only has 4, then it starts to attempt to draw a 5th quad and we get all manner of issues (index out of bounds for example).

The render method, updateLogic method and the onTouchEvent methods are all declared as synchronized, but I'm still getting the issue.

I'm not really sure how to go about ensuring the this object (the instance of StoreList and everything within it and it's 'thisList' array) can only be updated from one thread at a time.

The questions that I've seen relating to concurrency issues have all been about protecting a method from being called by multiple threads and not objects, so I'm a little confused.

Would appreciate any guidance.

Why not use synchronized block on StoreItems instead of synchronizing the insert/update methods. The synchronized block would guarantee that only one thread may execute insert code block, or any other code block(say update) which is synchronized on the same object (ie StoreItems) at any time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM