Concurrency-Safe Adapter

Source: Internet
Author: User

Problem

Adapter data itself to use for GetView and GetCount, and the program is getcount in different methods of continuous getview, this brings a problem: After GetCount, the data is deleted by other threads, in the GetView when the cross-border

Solution Ideas
    1. Set up a concurrentadapter, the inside with two lists to store data, one is the external operation additions and deletions, a used for the actual drawing.
    2. When the external additions and deletions, temporarily do not change the internal list, so that there is no cross-border
    3. After the internal getcount again, if you find that the list has been modified externally, copy it again from the external.
Code
 Public classconcurrentadapter<t> {//For external operation of list, external to its additions and deletions    PrivateList<t> objectscached=NewArraylist<t> ();//For adapter internal calculations, from external copy.    PrivateList<t> objects=NewArraylist<t> ();//For the number of cache list, when-1, indicates external modified list, need to update    Private intcount=-1; Public  int GetCount(){if(count==-1{synchronized (objectscached) {objects.clear ();                Objects.addall (objectscached); Count=objects.size ();returnCount }        }Else{returnCount }    } PublicTGetObject(intPosition) {returnObjects.Get(position); } Public void AddObject(TObject) {synchronized (objectscached) {Objectscached.add (Object); count=-1; }    } Public void addobjects(List<t> objects)            {synchronized (objectscached) {Objectscached.addall (objects); count=-1; }    } Public void setobjects(List<t> objects)            {synchronized (objectscached) {objectscached.clear ();            Objectscached.addall (objects); count=-1; }    } Public void Removeobject(TObject) {synchronized (objectscached) {Objectscached.remove (Object); count=-1; }    }}

Concurrency-Safe Adapter

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.