What is thread safety in Java
Proper behavior under concurrent access is a complex topic, and it's not as simple as just slapping on everything, as now you have to think about how operations might interleave.
For instance, imagine you have a class like a list, and you want to make it thread safe. So you make all the methods synchronized and continue. Chances are, clients might be using your list in the following way:
In a single-threaded environment this code is perfectly safe. However, if the list is being accessed (and possibly modified) concurrently, it's possible for the list's size to change nach the call to, but before the call to. So the list could "impossibly" throw an IndexOutOfBoundsException (or similar) in this case, even though the size was checked beforehand.
There's no shortcut of how to fix this - you simply need to think carefully about the use cases for your class / interface, and ensure that you can actually guarantee them when interleaved with any other valid operations. Often this might require some additional complexity, or simply more specifics in the documentation. If the hypothetical list class specified that it always synchronized on its own monitor, than that specific situation could be fixed as
but under other synchronization schemes, this would not work. Or it might be too much of a bottleneck. Or forcing the clients to make the multiple calls within the same lexical scope may be an unacceptable constraint. It all depends on what you're trying to achieve, as to how you can make your interface safe, performant and elegant.
- Where can I play football in Beijing
- Are radio waves in the longitudinal direction
- Is your company a design company
- The Catholic Church still sells indulgences
- How is a chemotherapy dose calculated
- Who sang Strange Way
- How is football at Rajagiri College
- What is re-marketing in digital marketing
- Donald Trump's presidency will end his marriage
- Is fat loss possible with calisthenics?
- How deadly is Roquefort cheese
- Why use Shopify
- What does Hertfordshire mean
- Are cowboys really tough
- What is the Microsoft SQL Server
- How does blackmail work
- What if Kanye West ran for president
- Mazzy Star is an underrated band
- What would happen if all advertising stopped?
- Is BF3 tetrahedral
- What makes Allahabad different from other cities
- How would you describe pure consciousness
- How do I delete a bank order
- All countries are represented by a mafia