OLD | NEW |
| (Empty) |
1 # Copyright 2015 The Chromium Authors. All rights reserved. | |
2 # Use of this source code is governed by a BSD-style license that can be | |
3 # found in the LICENSE file. | |
4 | |
5 import threading | |
6 | |
7 | |
8 class WeakConstant(object): | |
9 """A thread-safe, lazily initialized object. | |
10 | |
11 This does not support modification after initialization. The intended | |
12 constant nature of the object is not enforced, though, hence the "weak". | |
13 """ | |
14 | |
15 def __init__(self, initializer): | |
16 self._initialized = False | |
17 self._initializer = initializer | |
18 self._lock = threading.Lock() | |
19 self._val = None | |
20 | |
21 def read(self): | |
22 """Get the object, creating it if necessary.""" | |
23 if self._initialized: | |
24 return self._val | |
25 with self._lock: | |
26 if not self._initialized: | |
27 self._val = self._initializer() | |
28 self._initialized = True | |
29 return self._val | |
OLD | NEW |