Returns the stripes that correspond to the passed objects, in ascending (as per #getAt(int)) order. Thus, threads that use the stripes in the order returned by this method are guaranteed to not deadlock each other. It should be noted that using a Striped with relatively few st
(Iterable<?> keys)
| 150 | |
| 151 | |
| 152 | public Iterable<L> bulkGet(Iterable<?> keys) { |
| 153 | // Initially using the array to store the keys, then reusing it to store the respective L's |
| 154 | final Object[] array = Iterables.toArray(keys, Object.class); |
| 155 | if (array.length == 0) { |
| 156 | return ImmutableList.of(); |
| 157 | } |
| 158 | int[] stripes = new int[array.length]; |
| 159 | for (int i = 0; i < array.length; i++) { |
| 160 | stripes[i] = indexFor(array[i]); |
| 161 | } |
| 162 | Arrays.sort(stripes); |
| 163 | // optimize for runs of identical stripes |
| 164 | int previousStripe = stripes[0]; |
| 165 | array[0] = getAt(previousStripe); |
| 166 | for (int i = 1; i < array.length; i++) { |
| 167 | int currentStripe = stripes[i]; |
| 168 | if (currentStripe == previousStripe) { |
| 169 | array[i] = array[i - 1]; |
| 170 | } else { |
| 171 | array[i] = getAt(currentStripe); |
| 172 | previousStripe = currentStripe; |
| 173 | } |
| 174 | } |
| 175 | /* |
| 176 | * Note that the returned Iterable holds references to the returned stripes, to avoid |
| 177 | * error-prone code like: |
| 178 | * |
| 179 | * Striped<Lock> stripedLock = Striped.lazyWeakXXX(...)' |
| 180 | * Iterable<Lock> locks = stripedLock.bulkGet(keys); |
| 181 | * for (Lock lock : locks) { |
| 182 | * lock.lock(); |
| 183 | * } |
| 184 | * operation(); |
| 185 | * for (Lock lock : locks) { |
| 186 | * lock.unlock(); |
| 187 | * } |
| 188 | * |
| 189 | * If we only held the int[] stripes, translating it on the fly to L's, the original locks might |
| 190 | * be garbage collected after locking them, ending up in a huge mess. |
| 191 | */ |
| 192 | @SuppressWarnings("unchecked") // we carefully replaced all keys with their respective L's |
| 193 | List<L> asList = (List<L>) Arrays.asList(array); |
| 194 | return Collections.unmodifiableList(asList); |
| 195 | } |
| 196 | |
| 197 | // Static factories |
| 198 |