• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Freezing Sendable Objects
2
3Sendable objects can be frozen, making them read-only and preventing any additions, deletions, or modifications to their properties. Once frozen, these objects can be safely accessed across multiple concurrent instances without the need for locks. This is achieved using the [Object.freeze](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) method.
4
5## Usage Example
6
71. Encapsulate the **Object.freeze** method in a TS file.
8
9   ```ts
10   // helper.ts
11   export function freezeObj(obj: any) {
12     Object.freeze(obj);
13   }
14   ```
15
162. Call the **freeze** method to freeze an object and send it to a child thread.
17
18   ```ts
19   // Index.ets
20   import { freezeObj } from './helper';
21   import { worker } from '@kit.ArkTS';
22
23   @Sendable
24   export class GlobalConfig {
25     // Configuration properties and methods
26     init() {
27       // Initialization logic
28       freezeObj(this) // Freeze the object after the initialization is complete.
29     }
30   }
31
32   @Entry
33   @Component
34   struct Index {
35     build() {
36       Column() {
37         Text("Sendable freezeObj Test")
38           .id('HelloWorld')
39           .fontSize(50)
40           .fontWeight(FontWeight.Bold)
41           .onClick(() => {
42             let gConifg = new GlobalConfig();
43             gConifg.init();
44             const workerInstance = new worker.ThreadWorker('entry/ets/workers/Worker.ets', { name: "Worker1" });
45             workerInstance.postMessage(gConifg);
46           })
47       }
48       .height('100%')
49       .width('100%')
50     }
51   }
52   ```
53
543. Perform operations on the frozen object directly in the child thread without locking.
55
56   ```ts
57   // Worker.ets
58   import { ErrorEvent, MessageEvents, ThreadWorkerGlobalScope, worker } from '@kit.ArkTS';
59   import { GlobalConfig } from '../pages/Index';
60
61   const workerPort: ThreadWorkerGlobalScope = worker.workerPort;
62   workerPort.onmessage = (e: MessageEvents) => {
63     let gConfig: GlobalConfig = e.data;
64     // Use the gConfig object.
65   }
66   ```
67