3 ms·
One of the most frequently trumpeted cases for immutability is WRT thread safety. Is it me, or does this need come up rarely in practice relative to the forcefu
by danieldk 11y ago
One of the most frequently trumpeted cases for immutability is WRT thread safety. Is it me, or does this need come up rarely in practice relative to the forcefulness of arguments to make everything immutable? I get that it depends on your project, etc. But, I'm talking overall.
Yes, I more than once had to fix code in an natural language processing library, because multi-threaded Jersey services led to either crashes or partial annotations literally ending up in the wrong request. In the cases where I had access to the code, I rewrote the classes to be immutable (all state is created and passed between method calls), which fixed it.
In one natural language parser that we couldn't patch, I had to create one full parser instance per thread (weighing in at ~1-2GB), because the class was mutable and did not use correct locking. (So, we ended up creating a couple of parsers at startup and putting them in an object pool.)
- unclebucknasty 11y agoWhat you're describing are just plain bad coding practices by people who didn't understand concurrency. Proper locking and synchronization are the real fixes. Again, that's not to say that immutability never has a place.
- GFK_of_xmaspast 11y agoAs a C++ programmer, I make sure that things that can reasonably be const are const, because that reduces the number of places where things can go wrong. That said, sometimes state simply has to change, and anything else is just ideology.
- danieldk 11y agoConcurrency is hard. Immutability skates around the whole problem. A parser should be immutable, parsing state should be limited to a particular invocation of the parser. Of course, mutable state cannot be abolished everywhere (often for efficiency reasons). In such cases, you should indeed understand the concurrency primitives.