Thread safety when iterating through an ArrayList using foreach

后端 未结 4 1692
既然无缘
既然无缘 2021-01-02 09:25

I\'ve got an ArrayList which is being instantiated and populated on the background thread (I use it to store the Cursor data). At the same time it

4条回答
  •  被撕碎了的回忆
    2021-01-02 09:54

    java synchronized block http://www.tutorialspoint.com/java/java_thread_synchronization.htm

    class SomeClass {
    
        private final Context mContext;
        private List mList = null;
    
        SomeClass(Context context) {
            mContext = context;
        }
    
        public void populateList() {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    synchronized(SomeClass.this){
                        mList = new ArrayList<>();
    
                        Cursor cursor = mContext.getContentResolver().query(
                                DataProvider.CONTENT_URI, null, null, null, null);
                        try {
                            while (cursor.moveToNext()) {
                                mList.add(cursor.getString(cursor.getColumnIndex(DataProvider.NAME)));
                            }
                        } catch (Exception e) {
                            Log.e("Error", e.getMessage(), e);
                        } finally {
                            if (cursor != null) {
                                cursor.close();
                            }
                        }
                    }
                }
            }).start();
        }
    
        public boolean searchList(String query) { // Invoked on the main thread
        synchronized(SomeClass.this){
                if (mList != null) {
                    for (String name : mList) {
                        if (name.equals(query) {
                            return true;
                        }
                    }
                }
    
                return false;
            }
        }
    }
    

提交回复
热议问题