Thread Safe and its link to Collections

Asked

Viewed 112 times

4

What comes to be thread safe, and what is your connection to data collections?

1 answer

4


How should you know, if more than one thread access the same object may occur competition problems (conflicts/inconsistency in the data that this object contains, that is, in the state of that object).

To say that a class is thread safe means to say that an object of this class can be accessed by more than one thread without these conflicts occurring.

A collection thread safe has methods for you to access or to (browse) your data without these conflicts occur.

Examples of situations where it is recurrent to use a collection thread-safe:

  1. In a mobile chat where you maintain a mailing list, a message can be added by the user, which usually occurs in the main thread, or you can get a message via another user’s network, what usually occurs in a secondary thread that awaits the arrival of messages. As it is the same list, the insertion of messages should be done in a way thread-safe.

  2. Another similar example, and also for mobile, is a tracking app that maintains a list of positions captured by GPS and tries periodically to send them to a server. The list can either store new objects (positions that GPS obtains from geopositioning satellites) or remove objects (positions that have already been sent to the server).

  3. Not directly related to a collection, but similar: the Android database is Sqlite, which is not thread-safe. If you have more than one thread wanting to access it concurrently, you will need to maintain a monitor/lock to prevent an exception if the database is accessed by both at the same time.

  • 2

    Do you have any practical example of this, or any situation where it is recurrent to use a collection with thread safe?

  • I updated my answer with a few examples.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.