Timeline for Thread-safely transforming a value in a mutable map
Current License: CC BY-SA 3.0
10 events
when toggle format | what | by | license | comment | |
---|---|---|---|---|---|
Aug 13, 2013 at 20:56 | comment | added | som-snytt | @RégisJean-Gilles Yes. I +1 this + yours, which I mashed up to some effect below, for some value of some. | |
Aug 11, 2013 at 16:22 | comment | added | Régis Jean-Gilles | Of course if this is literaly just to perform increments, this is overkill. For something more substantial in terms of computation, that is a nice enough solution. A fully generic solution would actually use a fixed set of one-thread pools (a pool of thread pools) and just make sure that each instance of the map always uses the same one-threa pool. This would prevent the thread count from explosing (as the number of maps grow) while still ensuring that there is no thread-unsafe access. | |
Aug 11, 2013 at 14:29 | comment | added | som-snytt | I'm not sure I'd want to dedicate a thread to one counter, but maybe if it was doing other drudge work; a get could wait in a long queue. But if hourly rates correlate with SO rep, this is a great deal. Also satisfies the no-dependency requirement, if Akka is a dependency. | |
Aug 10, 2013 at 14:15 | comment | added | Régis Jean-Gilles | Yes, that was my whole point. This is much better now. Actually if OP can indeed adapt his code to use futures, this is the best solution in terms of ease of use and correctness (though not iintterms of speed). | |
Aug 10, 2013 at 13:03 | comment | added | Mushtaq Ahmed | c.counts is a mutable map so exposing it to the outside world is not a good idea. I updated the code by adding a get method and making map private. The gist is: all read/write to the mutable map must be guarded by ec. If that is not acceptable, use a concurrent data structure. | |
Aug 10, 2013 at 12:57 | history | edited | Mushtaq Ahmed | CC BY-SA 3.0 |
Added a get method to avoid unsafe access to the whole map from outside.
|
Aug 10, 2013 at 12:43 | comment | added | Régis Jean-Gilles |
But the thing is, the reading is done directly: when you access c.counts you are not using the ExecutionContext at all.
|
|
Aug 10, 2013 at 11:59 | comment | added | Mushtaq Ahmed | As I understand, all operations - read, write, mixed - that use ec as context will be thread safe. Ops outside that context will not be thread-safe. Will be glad to hear from others if this understanding is correct. | |
Aug 10, 2013 at 8:53 | comment | added | Régis Jean-Gilles | This is not thread safe at all. While you guarantee a single writer at a time, you can still have threads reading while the map is being modified | |
Aug 9, 2013 at 18:21 | history | answered | Mushtaq Ahmed | CC BY-SA 3.0 |