user611105
user611105

Reputation:

Can someone explain Thread Safety in layman terms?

Despite me reading wikipedia and such, I still don't really understand what Thread Safety means in a programming sense. Is anyone able to give some Java examples in layman terms? Such as what makes a thread safe vs a thread unsafe?

Thanks!

Upvotes: 3

Views: 580

Answers (3)

emory
emory

Reputation: 10891

I think it is helpful to think in terms of concrete things outside the computer. (Concurrent programming was being done long before the invention of digital computers.)

A car is a process. An intersection is a shared resource. If the light is green in multiple directions at the same time, then it is probably not thread safe.

Upvotes: 8

mamboking
mamboking

Reputation: 4637

It's not that the thread is safe or not. It's how state in your objects are protected from being updated by multiple threads. So, it's safe if only 1 thread can update a variable at a time so that you don't end up with some kind of inconsistent or unpredictable state.

An example of thread unsafe: You have an object that has an instance variable that stores a list of items that 1 method in that object uses to hold results of computations that it will return when it finishes. If two threads call that method at the same time, both instances of that running method will try to update the same list so the methods' results will be intermingled.

Upvotes: 0

Oded
Oded

Reputation: 499012

It is a fuzzy term - there is no exact agreement on what it actually means.

Normally, however, people mean code that can be called from multiple threads concurrently without a chance of errors.

That is - code is considered thread safe if it can be called from multiple threads at the same time and is guaranteed not to cause errors.

Upvotes: 2

Related Questions