Overview of concurrency
If more than one Gosu thread interacts with data structures that another thread needs, you must ensure that you protect data access to avoid data corruption. The requirement to support concurrent access from multiple threads is called concurrency. Code that can safely get or set concurrently accessed data is called thread-safe.
Gosu provides the following concurrency APIs:
- Support for Java monitor locks, reentrant locks, and custom reentrant objects
- Gosu provides access to Java-based classes for monitor locks and reentrant locks in the
Java package
java.util.concurrent. Gosu provides straightforward access to these classes withusingclauses that also properly handle cleanup if exceptions occur. Additionally, Gosu provides a straightforward way to create custom Gosu objects that support reentrant object handling, as shown in the following example. The following Gosu code that uses theusingkeyword shows the compact readable syntax for using Java-defined reentrant locks.// In your class definition, define a static variable lock static var _lock = new ReentrantLock() // A property get function uses the lock and calls another method for the main work property get SomeProp() : Object { using (_lock) { return _someVar.someMethod() // Do your work here and Gosu synchronizes it, and handles cleanup } } - Scoping classes (pre-scoped maps)
- Scope-related utilities in the class gw.api.web.Scopes provide synchronization and protect access to shared data. These APIs return Map objects that you can use to safely get and put data by using different scope semantics.
- Lazy concurrent variables
- The LazyVar class in
gw.util.concurrentimplements what is known as a lazy variable. Gosu does not construct a lazy variable until the first time any code uses the variable. For example, the following code is part of a class definition that defines the object instance. For example, Gosu does not run the following Gosu block that creates anArrayListuntil the first usage of the variable:var _lazy = LazyVar.make(\-> new ArrayList<String>()) - Concurrent cache
- The Cache class in
gw.util.concurrentdeclares a cache of values that you can look up quickly and in a thread-safe way. A Cache object provides a concurrent cache similar to a Least Recently Used (LRU) cache. To use the cache, call the get method with an argument of the input value, which is the key. If the value is in the cache, the get method returns the value from the cache. If the value is not cached, Gosu calls the block and calculates the value from the key, and then caches the result. For example:print(myCache.get("Hello world")
See also
