This example demonstrates the uniqueness of instances based on the per-THREAD lifestyle policy. When a component is assiciated with the THREAD lifestyle policy the component instance is assigned as a thread local variable. As such, any objects accessing the componet instance will do so in a sequential manner. In the example we deploy a series of seperate threads and for each thread we access the parts interface n times. Each access within a given thread returns the same instance but each thread has a differnet instance allocated to it.
tutorial/components/thread:
Demo.java | A component that that established n threads, and makes multiple requests against the internal parts instance. The number of threads and per-thread hits is controlled by respective context values. |
Gizmo.java | A test component we will use as the solution to the demo context criteria. |
DemoTestCase.java | The testcase. |
To demonstrate the impact of the lifestyle policy we can update our project defintition and declare an explicit lifestyle. In this case we assign the TRANSIENT lifestyle policy to the widget component.
component definition::
<component xmlns="dpml:metro" class="org.acme.Demo" name="demo"> <context> <entry key="threadCount" value="3"/> <entry key="accessCount" value="2"/> </context> <parts> <component key="gizmo" type="org.acme.Gizmo" lifestyle="thread"/> </parts> </component>
The following debug level logging thread name and resolved instance. Analysis of the results demonstrates the resolution of a single instance for any given thread.
test: [junit] Executing forked test. [junit] Running org.acme.test.DemoTestCase [junit] Tests run: 1, Failures: 0, Errors: 0, Time elapsed: 0.89 sec [junit] [15100] [INFO ] (demo): gizmo (Thread[0,5,main]) [31365828] [junit] [15100] [INFO ] (demo): gizmo (Thread[2,5,main]) [25345246] [junit] [15100] [INFO ] (demo): gizmo (Thread[1,5,main]) [26530674] [junit] [15100] [INFO ] (demo): gizmo (Thread[1,5,main]) [26530674] [junit] [15100] [INFO ] (demo): gizmo (Thread[2,5,main]) [25345246] [junit] [15100] [INFO ] (demo): gizmo (Thread[0,5,main]) [31365828]
Components assiated with a per-thread lifestyle are not shared within a given thread. As such all method invocations are sequential and the component implementation does not need to be concerned with concurreny.