1# @arkts.utils (ArkTS Utils) 2 3The Utils module provides a variety of ArkTS utility functions. 4 5> **NOTE** 6> 7> The initial APIs of this module are supported since API version 12. Newly added APIs will be marked with a superscript to indicate their earliest API version. 8> 9> This module can be imported only to ArkTS files (with the file name extension .ets). 10 11## Modules to Import 12 13```ts 14import { ArkTSUtils } from '@kit.ArkTS' 15``` 16 17## ArkTSUtils.locks 18 19To avoid data races between concurrent instances, the ArkTS common library introduces **AsyncLock**. Passing **AsyncLock** objects by reference across concurrent instances is supported. 20 21ArkTS supports asynchronous operations, and blocking locks are prone to deadlocks. Therefore, only asynchronous locks (non-blocking locks) are used in ArkTS. 22 23The method that uses an asynchronous lock must be marked as **async**, and the caller must use **await** in the call to ensure the correct call sequence. As a result, all outer functions are marked as **async**. 24 25### AsyncLockCallback 26 27type AsyncLockCallback\<T> = () => T | Promise\<T> 28 29A supplementary type alias that represents the callback in all the overloads of [lockAsync](#lockasync). 30 31**Atomic service API**: This API can be used in atomic services since API version 12. 32 33**System capability**: SystemCapability.Utils.Lang 34 35### AsyncLock 36 37A class that implements an asynchronous lock and allows asynchronous operations to be performed under a lock. This class is decorated by [@Sendable](../../arkts-utils/arkts-sendable.md). 38 39#### Properties 40 41**Atomic service API**: This API can be used in atomic services since API version 12. 42 43**System capability**: SystemCapability.Utils.Lang 44 45| Name| Type | Read-Only| Optional| Description | 46| ---- | ------ | ---- | ---- | ---------- | 47| name | string | Yes | No | Name of the lock.| 48 49**Example** 50 51```ts 52// Example 1 53@Sendable 54class A { 55 count_: number = 0; 56 async getCount(): Promise<number> { 57 let lock: ArkTSUtils.locks.AsyncLock = ArkTSUtils.locks.AsyncLock.request("lock_1"); 58 return lock.lockAsync(() => { 59 return this.count_; 60 }) 61 } 62 async setCount(count: number) { 63 let lock: ArkTSUtils.locks.AsyncLock = ArkTSUtils.locks.AsyncLock.request("lock_1"); 64 await lock.lockAsync(() => { 65 this.count_ = count; 66 }) 67 } 68} 69 70// Example 2 71@Sendable 72class A { 73 count_: number = 0; 74 lock_: ArkTSUtils.locks.AsyncLock = new ArkTSUtils.locks.AsyncLock(); 75 async getCount(): Promise<number> { 76 return this.lock_.lockAsync(() => { 77 return this.count_; 78 }) 79 } 80 async setCount(count: number) { 81 await this.lock_.lockAsync(() => { 82 this.count_ = count; 83 }) 84 } 85} 86 87@Concurrent 88async function foo(a: A) { 89 await a.setCount(10) 90} 91``` 92 93#### constructor 94 95constructor() 96 97Default constructor used to create an asynchronous lock. 98 99**Atomic service API**: This API can be used in atomic services since API version 12. 100 101**System capability**: SystemCapability.Utils.Lang 102 103**Return value** 104 105| Type | Description | 106| ----------------------- | ------------------ | 107| [AsyncLock](#asynclock) | **AsyncLock** instance created.| 108 109**Example** 110 111```ts 112let lock = new ArkTSUtils.locks.AsyncLock(); 113``` 114 115#### request 116 117static request(name: string): AsyncLock 118 119Finds or creates (if not found) an **AsyncLock** instance with the specified name. 120 121**Atomic service API**: This API can be used in atomic services since API version 12. 122 123**System capability**: SystemCapability.Utils.Lang 124 125**Parameters** 126 127| Name| Type | Mandatory| Description | 128| ---- | ------ | ---- | -------------------------------- | 129| name | string | Yes | Name of the lock.| 130 131**Return value** 132 133| Type | Description | 134| ----------------------- | -------------------------------- | 135| [AsyncLock](#asynclock) | **AsyncLock** instance found or created.| 136 137**Example** 138 139```ts 140let lockName = 'isAvailableLock'; 141let lock = ArkTSUtils.locks.AsyncLock.request(lockName); 142``` 143 144#### query 145 146static query(name: string): AsyncLockState 147 148Queries information about an asynchronous lock. 149 150**Atomic service API**: This API can be used in atomic services since API version 12. 151 152**System capability**: SystemCapability.Utils.Lang 153 154**Parameters** 155 156| Name| Type | Mandatory| Description | 157| ---- | ------ | ---- | ------------------------------------------------------------------------------------------------------------------------ | 158| name | string | Yes | Name of the lock. Only locks obtained through the [request](#request) API can be queried, meaning that the lock name must match the parameter passed to the [request](#request) API.| 159 160**Return value** 161 162| Type | Description | 163| --------------------------------- | ---------------------------------- | 164| [AsyncLockState](#asynclockstate) | **AsyncLockState** instance that contains the lock state information.| 165 166**Error codes** 167 168For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md). 169 170| ID| Error Message | 171| -------- | ------------- | 172| 401 | The input parameters are invalid. | 173| 10200030 | The lock does not exist. | 174 175**Example** 176 177```ts 178// You have created a lock somewhere else. 179// let lock = ArkTSUtils.locks.AsyncLock.request("queryTestLock"); 180let state = ArkTSUtils.locks.AsyncLock.query('queryTestLock'); 181if (!state) { 182 throw new Error('Test failed: A valid state is expected, but the obtained state is '+ state); 183} 184let pending: ArkTSUtils.locks.AsyncLockInfo[] = state.pending; 185let held: ArkTSUtils.locks.AsyncLockInfo[] = state.held; 186``` 187 188#### queryAll 189 190static queryAll(): AsyncLockState[] 191 192Queries information about all existing asynchronous locks. 193 194**Atomic service API**: This API can be used in atomic services since API version 12. 195 196**System capability**: SystemCapability.Utils.Lang 197 198**Return value** 199 200| Type | Description | 201| ----------------------------------- | -------------------------------- | 202| [AsyncLockState](#asynclockstate)[] | **AsyncLockState** array that contains the lock state information.| 203 204**Example** 205 206```ts 207let states: ArkTSUtils.locks.AsyncLockState[] = ArkTSUtils.locks.AsyncLock.queryAll(); 208if (states.length === 0) { 209 throw new Error('Test failed: At least one state is expected, but what got is ' + states.length); 210} 211``` 212 213#### lockAsync 214 215lockAsync\<T>(callback: AsyncLockCallback\<T>): Promise\<T> 216 217Performs an operation under a lock. This API acquires the lock, executes the callback, and releases the lock. The callback is executed asynchronously in the same thread where [lockAsync](#lockasync) was called. 218 219**Atomic service API**: This API can be used in atomic services since API version 12. 220 221**System capability**: SystemCapability.Utils.Lang 222 223**Parameters** 224 225| Name | Type | Mandatory| Description | 226| -------- | --------------------------------------- | ---- | ---------------------- | 227| callback | [AsyncLockCallback\<T>](#asynclockcallback) | Yes | Callback to be executed after a lock is acquired.| 228 229**Return value** 230 231| Type | Description | 232| ----------- | --------------------------- | 233| Promise\<T> | Promise that will be resolved after the callback is executed.| 234 235**Error codes** 236 237For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md). 238 239| ID| Error Message | 240| -------- | ------------- | 241| 401 | The input parameters are invalid. | 242| 10200030 | The lock does not exist. | 243 244**Example** 245 246```ts 247let lock = new ArkTSUtils.locks.AsyncLock(); 248let p1 = lock.lockAsync<void>(() => { 249 // Perform an operation. 250}); 251``` 252 253#### lockAsync 254 255lockAsync\<T>(callback: AsyncLockCallback\<T>, mode: AsyncLockMode): Promise\<T> 256 257Performs an operation under a lock. This API acquires the lock, executes the callback, and releases the lock. The callback is executed asynchronously in the same thread where [lockAsync](#lockasync) was called. 258 259**Atomic service API**: This API can be used in atomic services since API version 12. 260 261**System capability**: SystemCapability.Utils.Lang 262 263**Parameters** 264 265| Name | Type | Mandatory| Description | 266| -------- | --------------------------------------- | ---- | ---------------------- | 267| callback | [AsyncLockCallback\<T>](#asynclockcallback) | Yes | Callback to be executed after a lock is acquired.| 268| mode | [AsyncLockMode](#asynclockmode) | Yes | Mode of the lock. | 269 270**Return value** 271 272| Type | Description | 273| ----------- | --------------------------- | 274| Promise\<T> | Promise that will be resolved after the callback is executed.| 275 276**Error codes** 277 278For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md). 279 280| ID| Error Message | 281| -------- | ------------- | 282| 401 | The input parameters are invalid. | 283| 10200030 | The lock does not exist. | 284 285**Example** 286 287```ts 288let lock = new ArkTSUtils.locks.AsyncLock(); 289let p1 = lock.lockAsync<void>(() => { 290 // Perform an operation. 291}, ArkTSUtils.locks.AsyncLockMode.EXCLUSIVE); 292``` 293 294#### lockAsync 295 296lockAsync\<T, U>(callback: AsyncLockCallback\<T>, mode: AsyncLockMode, options: AsyncLockOptions\<U>): Promise\<T | U> 297 298Performs an operation under a lock. This API acquires the lock, executes the callback, and releases the lock. The callback is executed asynchronously in the same thread where [lockAsync](#lockasync) was called. An optional timeout value can be provided in [AsyncLockOptions](#asynclockoptions). If a lock is not acquired before timeout, **lockAsync** returns a projected Promise with a **BusinessError** instance. In this instance, the error message contains information about the locks being held and in the waiting state, as well as possible deadlock warnings. 299 300**Atomic service API**: This API can be used in atomic services since API version 12. 301 302**System capability**: SystemCapability.Utils.Lang 303 304**Parameters** 305 306| Name | Type | Mandatory| Description | 307| -------- | ----------------------------------------- | ---- | ---------------------- | 308| callback | [AsyncLockCallback\<T>](#asynclockcallback) | Yes | Callback to be executed after a lock is acquired.| 309| mode | [AsyncLockMode](#asynclockmode) | Yes | Mode of the lock. | 310| options | [AsyncLockOptions\<U>](#asynclockoptions) | Yes | Options of the lock. | 311 312**Return value** 313 314| Type | Description | 315| ---------------- | -------------------------------------------------- | 316| Promise\<T \| U> | Promise that will be resolved after the callback is executed, or rejected in the case of timeout.| 317 318**Error codes** 319 320For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md). 321 322| ID| Error Message | 323| -------- | ----------------- | 324| 401 | The input parameters are invalid. | 325| 10200030 | The lock does not exist. | 326| 10200031 | Timeout exceeded. | 327 328**Example** 329 330```ts 331let lock = new ArkTSUtils.locks.AsyncLock(); 332let options = new ArkTSUtils.locks.AsyncLockOptions<void>(); 333options.timeout = 1000; 334let p: Promise<void> = lock.lockAsync<void, void>( 335 () => { 336 // Perform an operation. 337 }, 338 ArkTSUtils.locks.AsyncLockMode.EXCLUSIVE, 339 options 340); 341``` 342 343### AsyncLockMode 344 345Enumerates the modes of an asynchronous lock. 346 347**Atomic service API**: This API can be used in atomic services since API version 12. 348 349**System capability**: SystemCapability.Utils.Lang 350 351| Name | Value | Description | 352| --------- | --- | -------------------------------------------------------- | 353| SHARED | 1 | Shared lock mode, in which multiple threads can run at the same time. | 354| EXCLUSIVE | 2 | Exclusive lock mode, in which a thread can run only when it exclusively acquires the lock.| 355 356**Example** 357 358```ts 359let lock = new ArkTSUtils.locks.AsyncLock(); 360// shared0 can acquire the lock and start execution. 361lock.lockAsync(async () => { 362 console.info('shared0'); 363 await new Promise<void>((resolve) => setTimeout(resolve, 1000)); 364}, ArkTSUtils.locks.AsyncLockMode.SHARED); 365// shared1 can acquire the lock and start execution without waiting for shared0. 366lock.lockAsync(async () => { 367 console.info('shared1'); 368 await new Promise<void>((resolve) => setTimeout(resolve, 1000)); 369}, ArkTSUtils.locks.AsyncLockMode.SHARED); 370// exclusive0 can acquire the lock and start execution after shared0 and shared1 are executed. 371lock.lockAsync(async () => { 372 console.info('exclusive0'); 373 await new Promise<void>((resolve) => setTimeout(resolve, 1000)); 374}, ArkTSUtils.locks.AsyncLockMode.EXCLUSIVE); 375// shared2 can acquire the lock and start execution after exclusive0 is executed. 376lock.lockAsync(async () => { 377 console.info('shared2'); 378 await new Promise<void>((resolve) => setTimeout(resolve, 1000)); 379}, ArkTSUtils.locks.AsyncLockMode.SHARED); 380// shared3 can acquire the lock and start execution after exclusive0 is executed, but not after shared2 is executed. 381lock.lockAsync(async () => { 382 console.info('shared3'); 383 await new Promise<void>((resolve) => setTimeout(resolve, 1000)); 384}, ArkTSUtils.locks.AsyncLockMode.SHARED); 385``` 386 387### AsyncLockOptions 388 389class AsyncLockOptions\<T> 390 391Class that implements the asynchronous lock options. 392 393**Atomic service API**: This API can be used in atomic services since API version 12. 394 395**System capability**: SystemCapability.Utils.Lang 396 397#### constructor 398 399constructor() 400 401Default constructor used to create an **AsyncLockOptions** instance with the default values for all properties. 402 403**Atomic service API**: This API can be used in atomic services since API version 12. 404 405**System capability**: SystemCapability.Utils.Lang 406 407**Return value** 408 409| Type | Description | 410| ------------------------------------- | ---------------------- | 411| [AsyncLockOptions](#asynclockoptions) | **AsyncLockOptions** instance created.| 412 413**Example** 414 415```ts 416let s: ArkTSUtils.locks.AbortSignal<string> = { aborted: false, reason: 'Aborted' }; 417let options = new ArkTSUtils.locks.AsyncLockOptions<string>(); 418options.isAvailable = false; 419options.signal = s; 420``` 421 422#### Properties 423 424| Name | Type | Read-Only| Optional| Description | 425| ----------- | ------------------------------------- | ---- | ---- | ------------------------------------------------------------------------------------------------------------------------- | 426| isAvailable | boolean | No | No | Whether the lock is available. If the value is **true**, a lock is granted only when it is not held. If the value is **false**, a lock is granted once it is released. The default value is **false**.| 427| signal | [AbortSignal\<T>](#abortsignal)\|null | No | No | Signal used to abort an asynchronous operation. If **signal.aborted** is **true**, the lock request is discarded. If **signal.aborted** is **false**, the request keeps waiting. If **signal.aborted** is **null**, the request is queued normally. The default value is **null**. | 428| timeout | number | No | No | Timeout duration for the lock operation, in milliseconds. If the value is greater than zero and the operation exceeds this duration, [lockAsync](#lockasync) returns a rejected Promise. The default value is **0**. | 429 430### AsyncLockState 431 432A class used to store information about all lock operations currently performed on an **AsyncLock** instance. 433 434**Atomic service API**: This API can be used in atomic services since API version 12. 435 436**System capability**: SystemCapability.Utils.Lang 437 438#### Properties 439 440| Name | Type | Read-Only| Optional| Description | 441| ------- | --------------------------------- | ---- | ---- | ---------------- | 442| held | [AsyncLockInfo[]](#asynclockinfo) | No | No | Information about the lock being held. | 443| pending | [AsyncLockInfo[]](#asynclockinfo) | No | No | Information about the lock in the waiting state.| 444 445### AsyncLockInfo 446 447Describes the information about a lock. 448 449**Atomic service API**: This API can be used in atomic services since API version 12. 450 451**System capability**: SystemCapability.Utils.Lang 452 453#### Properties 454 455| Name | Type | Read-Only| Optional| Description | 456| --------- | ------------------------------- | ---- | ---- | --------------------------------------------------------- | 457| name | string | No | No | Name of the lock. | 458| mode | [AsyncLockMode](#asynclockmode) | No | No | Mode of the lock. | 459| contextId | number | No | No | Context identifier of the caller of [AsyncLockMode](#asynclockmode).| 460 461### AbortSignal 462 463A class that implements a signal used to abort an asynchronous operation. An instance of this class must be accessed in the same thread it creates. Otherwise, undefined behavior occurs. 464 465**Atomic service API**: This API can be used in atomic services since API version 12. 466 467**System capability**: SystemCapability.Utils.Lang 468 469#### Properties 470 471| Name | Type | Read-Only| Optional| Description | 472| ------- | ------- | ---- | ---- | ---------------------------------------------------------------- | 473| aborted | boolean | No | No | Whether to abort the asynchronous operation. The value **true** means to abort the asynchronous operation, and **false** means the opposite. | 474| reason | \<T> | No | No | Reason for abort. This value will be used in the rejected Promise returned by [lockAsync](#lockasync).| 475 476### ConditionVariable<sup>18+</sup> 477 478A class that implements asynchronous waiting, supporting asynchronous wait and notify operations. This class is decorated by [@Sendable](../../arkts-utils/arkts-sendable.md). 479 480**Atomic service API**: This API can be used in atomic services since API version 18. 481 482**System capability**: SystemCapability.Utils.Lang 483 484#### constructor<sup>18+</sup> 485 486constructor() 487 488Default constructor used to create an object for asynchronous wait and notify operations. 489 490**Atomic service API**: This API can be used in atomic services since API version 18. 491 492**System capability**: SystemCapability.Utils.Lang 493 494**Example** 495 496```ts 497let conditionVariable = new ArkTSUtils.locks.ConditionVariable(); 498``` 499 500#### request<sup>18+</sup> 501 502static request(name: string): ConditionVariable 503 504Looks up or creates (if not found) an object for asynchronous wait and notify operations based on the specified name. 505 506**Atomic service API**: This API can be used in atomic services since API version 18. 507 508**System capability**: SystemCapability.Utils.Lang 509 510**Parameters** 511 512| Name| Type | Mandatory| Description | 513| ---- | ------ | ---- | -------------------------------- | 514| name | string | Yes | Name used to identify the object for asynchronous wait and notify operations.| 515 516**Return value** 517 518| Type | Description | 519| ----------------------- | -------------------------------- | 520| [ConditionVariable](#conditionvariable18) | Object for asynchronous wait and notify operations.| 521 522**Example** 523 524```ts 525let conditionVariable = ArkTSUtils.locks.ConditionVariable.request("conditionName"); 526``` 527 528#### wait<sup>18+</sup> 529 530wait(): Promise\<void> 531 532Asynchronously waits until notified. This API uses a promise to return the result. 533 534**Atomic service API**: This API can be used in atomic services since API version 18. 535 536**System capability**: SystemCapability.Utils.Lang 537 538**Return value** 539 540| Type | Description | 541| ----------- | --------------------------- | 542| Promise\<void> | Promise that returns no value.| 543 544**Example** 545 546```ts 547const conditionVariable: ArkTSUtils.locks.ConditionVariable = new ArkTSUtils.locks.ConditionVariable(); 548conditionVariable.wait().then(() => { 549 console.info(`Thread being awakened, then continue...`); // Output logs upon awakening. 550}); 551``` 552 553#### waitFor<sup>18+</sup> 554 555waitFor(timeout : number) : Promise\<void> 556 557Asynchronously waits for a specified duration or until notified. This API uses a promise to return the result. 558 559**Atomic service API**: This API can be used in atomic services since API version 18. 560 561**System capability**: SystemCapability.Utils.Lang 562 563**Parameters** 564 565| Name| Type | Mandatory| Description | 566| -------- | -------- | ---- | ---------- | 567| timeout | number | Yes | Duration to wait, in ms. The value is a positive integer.| 568 569**Return value** 570 571| Type | Description | 572| ----------- | --------------------------- | 573| Promise\<void> | Promise that returns no value.| 574 575**Example** 576 577```ts 578const conditionVariable: ArkTSUtils.locks.ConditionVariable = new ArkTSUtils.locks.ConditionVariable(); 579conditionVariable.waitFor(3000).then(() => { 580 console.info(`Thread being awakened, then continue...`); // Output logs upon awakening. 581}); 582``` 583 584#### notifyAll<sup>18+</sup> 585 586notifyAll() : void 587 588Notifies all waiting threads. 589 590**Atomic service API**: This API can be used in atomic services since API version 18. 591 592**System capability**: SystemCapability.Utils.Lang 593 594**Example** 595 596```ts 597const conditionVariable: ArkTSUtils.locks.ConditionVariable = new ArkTSUtils.locks.ConditionVariable(); 598conditionVariable.waitFor(3000).then(() => { 599 console.info(`Thread being awakened, then continue...`); // Output logs upon awakening. 600}); 601conditionVariable.notifyAll(); 602``` 603 604#### notifyOne<sup>18+</sup> 605 606notifyOne() : void 607 608Notifies the first waiting thread. 609 610**Atomic service API**: This API can be used in atomic services since API version 18. 611 612**System capability**: SystemCapability.Utils.Lang 613 614**Example** 615 616```ts 617const conditionVariable: ArkTSUtils.locks.ConditionVariable = new ArkTSUtils.locks.ConditionVariable(); 618conditionVariable.waitFor(3000).then(() => { 619 console.info(`Thread a being awakened, then continue...`); // Output logs upon awakening. 620}); 621conditionVariable.notifyOne(); 622``` 623 624## ArkTSUtils.ASON 625 626A utility class used to parse JSON strings into [sendable data](../../arkts-utils/arkts-sendable.md#sendable-data-types). ASON allows you to parse JSON strings and generate Sendable data for pass-by-reference across concurrent instances. It also supports conversion from Sendable data into JSON strings. 627 628### ISendable 629 630type ISendable = lang.ISendable 631 632**ISendable** is the parent type of all sendable types except null and undefined. It does not have any necessary methods or properties. 633 634**Atomic service API**: This API can be used in atomic services since API version 12. 635 636**System capability**: SystemCapability.Utils.Lang 637 638| Type| Description | 639| ------ | ------ | 640| [lang.ISendable](js-apis-arkts-lang.md#langisendable) | Parent type of all sendable types.| 641 642### Transformer 643 644type Transformer = (this: ISendable, key: string, value: ISendable | undefined | null) => ISendable | undefined | null 645 646Defines the type of the conversion result function. 647 648**Atomic service API**: This API can be used in atomic services since API version 12. 649 650**System capability**: SystemCapability.Utils.Lang 651 652**Parameters** 653 654| Name| Type | Mandatory| Description | 655| ------ | ------ | ---- | --------------- | 656| this | [ISendable](#isendable) | Yes| Object to which the key-value pair to parse belongs.| 657| key | string | Yes| Key to parse.| 658| value | [ISendable](#isendable) \| undefined \| null| Yes| Value of the key.| 659 660**Return value** 661 662| Type| Description| 663| -------- | -------- | 664| [ISendable](#isendable) \| undefined \| null | **ISendable** object, undefined, or null.| 665 666### BigIntMode 667 668Enumerates the modes for processing BigInt. 669 670**Atomic service API**: This API can be used in atomic services since API version 12. 671 672**System capability**: SystemCapability.Utils.Lang 673 674| Name| Value| Description | 675| ------ | ------ | --------------- | 676| DEFAULT | 0 |BigInt is not supported.| 677| PARSE_AS_BIGINT | 1 |Parses an integer that is less than -(2^53-1) or greater than (2^53-1) as BigInt.| 678| ALWAYS_PARSE_AS_BIGINT | 2 |Parses all integers as BigInt.| 679 680### ParseReturnType 681 682Enumerates the return types of the parsing result. 683 684**System capability**: SystemCapability.Utils.Lang 685 686| Name| Value| Description | 687| ------ | ------ | --------------- | 688| OBJECT | 0 |Returns a **SendableObject** object.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 689| MAP<sup>13+</sup> | 1 |Returns a **SendableMap** object.<br>**Atomic service API**: This API can be used in atomic services since API version 13.| 690 691### ParseOptions 692 693Describes the parsing options, which defines the BigInt processing mode and the return type of the parsing result. 694 695**Atomic service API**: This API can be used in atomic services since API version 12. 696 697**System capability**: SystemCapability.Utils.Lang 698 699| Name| Type| Mandatory| Description | 700| ------ | ------ | ---- | --------------- | 701| bigIntMode | [BigIntMode](#bigintmode) | Yes|Mode for processing BigInt.| 702| parseReturnType | [ParseReturnType](#parsereturntype) | Yes|Return type of the parsing result.| 703 704### parse 705 706parse(text: string, reviver?: Transformer, options?: ParseOptions): ISendable | null 707 708Parses a JSON string to generate ISendable data or null. 709 710**Atomic service API**: This API can be used in atomic services since API version 12. 711 712**System capability**: SystemCapability.Utils.Lang 713 714**Parameters** 715 716| Name| Type | Mandatory| Description | 717| ------ | ------ | ---- | --------------- | 718| text | string | Yes| Valid JSON string.| 719| reviver | [Transformer](#transformer) | No| Conversion function. This parameter can be used to modify the value generated after parsing. The default value is undefined. Currently, only undefined can be passed in.| 720| options | [ParseOptions](#parseoptions) | No| Parsing options. This parameter is used to control the type of the parsing result. The default value is undefined.| 721 722**Return value** 723 724| Type| Description| 725| -------- | -------- | 726| [ISendable](#isendable) \| null | ISendable data or **null** (if **null** is passed in).| 727 728**Error codes** 729 730For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 731 732| ID| Error Message | 733| -------- | ------------- | 734| 401 | Parameter error. Invalid JSON string. | 735 736**Example** 737 738```ts 739import { lang } from '@kit.ArkTS'; 740import { collections } from '@kit.ArkTS'; 741 742type ISendable = lang.ISendable; 743let jsonText = '{"name": "John", "age": 30, "city": "ChongQing"}'; 744let obj = ArkTSUtils.ASON.parse(jsonText) as ISendable; 745console.info((obj as object)?.["name"]); 746// Expected output: 'John' 747console.info((obj as object)?.["age"]); 748// Expected output: 30 749console.info((obj as object)?.["city"]); 750// Expected output: 'ChongQing' 751 752let options: ArkTSUtils.ASON.ParseOptions = { 753 bigIntMode: ArkTSUtils.ASON.BigIntMode.PARSE_AS_BIGINT, 754 parseReturnType: ArkTSUtils.ASON.ParseReturnType.OBJECT, 755} 756let numberText = '{"largeNumber":112233445566778899}'; 757let numberObj = ArkTSUtils.ASON.parse(numberText,undefined,options) as ISendable; 758 759console.info((numberObj as object)?.["largeNumber"]); 760// Expected output: 112233445566778899 761 762let options2: ArkTSUtils.ASON.ParseOptions = { 763 bigIntMode: ArkTSUtils.ASON.BigIntMode.PARSE_AS_BIGINT, 764 parseReturnType: ArkTSUtils.ASON.ParseReturnType.MAP, 765 } 766let mapText = '{"largeNumber":112233445566778899}'; 767let map = ArkTSUtils.ASON.parse(mapText,undefined,options2); 768console.info("map is " + map); 769// Expected output: map is [object SendableMap] 770console.info("largeNumber is " + (map as collections.Map<string,bigint>).get("largeNumber")); 771// Expected output: largeNumber is 112233445566778899 772``` 773 774 775### stringify 776 777stringify(value: Object | null | undefined): string 778 779Converts ArkTS object data into a JSON string, with additional support for Map and Set types. 780 781> **NOTE** 782> 783> Since API 18, the parameter type is changed to Object. In versions earlier than API 18, only the ISendable type is supported. 784 785**Atomic service API**: This API can be used in atomic services since API version 18. 786 787**System capability**: SystemCapability.Utils.Lang 788 789**Parameters** 790 791| Name| Type| Mandatory| Description| 792| -------- | -------- | -------- | -------- | 793| value | Object \| null \| undefined | Yes| ArkTS object data.| 794 795**Return value** 796 797| Type| Description| 798| -------- | -------- | 799| string | JSON string.| 800 801**Error codes** 802 803For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 804 805| ID| Error Message | 806| -------- | ------------- | 807| 401 | Parameter error. Invalid ArkTS value. | 808 809**Example** 810 811```ts 812import { ArkTSUtils, collections, HashMap, HashSet } from '@kit.ArkTS'; 813 814let hashMap = new HashMap<string,string>(); 815hashMap.set("ha","a"); 816hashMap.set("sh","b"); 817hashMap.set("map","c"); 818let str1 = ArkTSUtils.ASON.stringify(hashMap); 819console.info(str1); 820// Expected output: '{"sh":"b","ha":"a","map":"c"}' 821let hashSet = new HashSet<string>(); 822hashSet.add("ha"); 823hashSet.add("sh"); 824hashSet.add("set"); 825let str2 = ArkTSUtils.ASON.stringify(hashSet); 826console.info(str2); 827// Expected output: '["set","sh","ha"]' 828let map = new Map<string,string>(); 829map.set("m","a"); 830map.set("a","b"); 831map.set("p","c"); 832let str3 = ArkTSUtils.ASON.stringify(map); 833console.info(str3); 834// Expected output: '{"m":"a","a":"b","p":"c"}' 835let set = new Set<string>(); 836set.add("s"); 837set.add("e"); 838set.add("t"); 839let str4 = ArkTSUtils.ASON.stringify(set); 840console.info(str4); 841// Expected output: '["s","e","t"]' 842let sendableMap = new collections.Map<string,string>(); 843sendableMap.set("send","a"); 844sendableMap.set("able","b"); 845sendableMap.set("map","c"); 846let str5 = ArkTSUtils.ASON.stringify(sendableMap); 847console.info(str5); 848// Expected output: '{"send":"a","able":"b","map":"c"}' 849let sendableSet = new collections.Set<string>(); 850sendableSet.add("send"); 851sendableSet.add("able"); 852sendableSet.add("set"); 853let str6 = ArkTSUtils.ASON.stringify(sendableSet); 854console.info(str6); 855// Expected output: '["send","able","set"]' 856``` 857 858### isSendable 859 860isSendable(value: Object | null | undefined): boolean 861 862Checks whether the passed-in value is of the sendable data type. 863 864**Atomic service API**: This API can be used in atomic services since API version 12. 865 866**System capability**: SystemCapability.Utils.Lang 867 868**Parameters** 869 870| Name| Type| Mandatory| Description| 871| -------- | -------- | -------- | -------- | 872| value | Object \| null \| undefined | Yes| Object to check.| 873 874**Return value** 875 876| Type| Description| 877| -------- | -------- | 878| boolean | Check result. The value **true** is returned if the passed-in value is of the sendable data type; otherwise, **false** is returned.| 879 880**Example** 881 882```ts 883import { ArkTSUtils } from '@kit.ArkTS'; 884 885@Sendable 886function sendableFunc() { 887 console.info("sendableFunc"); 888} 889 890if (ArkTSUtils.isSendable(sendableFunc)) { 891 console.info("sendableFunc is Sendable"); 892} else { 893 console.info("sendableFunc is not Sendable"); 894} 895// Expected output: 'SendableFunc is Sendable' 896``` 897 898## SendableLruCache<K, V><sup>18+</sup> 899 900Provides APIs to discard the least recently used data to make rooms for new elements when the cache is full. This class uses the Least Recently Used (LRU) algorithm, which believes that the recently used data may be accessed again in the near future and the least accessed data is the least valuable data and should be removed from the cache. **SendableLruCache** supports the Sendable feature, allowing it to store Sendable objects and ensuring safe cross-thread access. 901 902### Properties 903 904**Atomic service API**: This API can be used in atomic services since API version 18. 905 906**System capability**: SystemCapability.Utils.Lang 907 908| Name | Type | Read-Only| Optional| Description | 909| ------ | ------ | ---- | ---- | ---------------------- | 910| length | number | Yes | No | Total number of values in this cache.| 911 912**Example** 913 914```ts 915let pro = new ArkTSUtils.SendableLruCache<number, number>(); 916pro.put(2, 10); 917pro.put(1, 8); 918let result = pro.length; 919console.info('result = ' + result); 920// Expected output: result = 2 921``` 922 923### constructor<sup>18+</sup> 924 925constructor(capacity?: number) 926 927A constructor used to create a **SendableLruCache** instance. The default capacity of the cache is 64. 928 929**Atomic service API**: This API can be used in atomic services since API version 18. 930 931**System capability**: SystemCapability.Utils.Lang 932 933**Parameters** 934 935| Name | Type | Mandatory| Description | 936| -------- | ------ | ---- | ---------------------------- | 937| capacity | number | No | Capacity of the cache to create. The default value is **64**, and the maximum value is **2147483647**.| 938 939**Example** 940 941```ts 942let pro = new ArkTSUtils.SendableLruCache<number, number>(); 943``` 944 945### updateCapacity<sup>18+</sup> 946 947updateCapacity(newCapacity: number): void 948 949Changes the cache capacity. If the total number of values in the cache exceeds the specified capacity, the least recently used key-value pairs are removed. 950 951**Atomic service API**: This API can be used in atomic services since API version 18. 952 953**System capability**: SystemCapability.Utils.Lang 954 955**Parameters** 956 957| Name | Type | Mandatory| Description | 958| ----------- | ------ | ---- | ---------------------------- | 959| newCapacity | number | Yes | New capacity of the cache. The maximum value is 2147483647. If the value is less than or equal to 0, an exception is thrown.| 960 961**Error codes** 962 963For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 964 965| ID | Error Message | 966| -------- | ------------------------------------------| 967| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified;2.Incorrect parameter types. | 968 969**Example** 970 971```ts 972let pro = new ArkTSUtils.SendableLruCache<number, number>(); 973pro.updateCapacity(100); 974``` 975 976### toString<sup>18+</sup> 977 978toString(): string 979 980Obtains the string representation of this cache. 981 982**Atomic service API**: This API can be used in atomic services since API version 18. 983 984**System capability**: SystemCapability.Utils.Lang 985 986**Return value** 987 988| Type | Description | 989| ------ | -------------------------- | 990| string | String representation of the cache, in the format of SendableLruCache[ maxSize = (maxSize), hits = (hitCount), misses = (missCount), hitRate = (hitRate) ], where **(maxSize)** indicates the maximum size of the cache, **(hitCount)** indicates the number of matched queries, **(missCount)** indicates the number of times that the number of mismatched queries, and **(hitRate)** indicates the matching rate.| 991 992**Example** 993 994```ts 995let pro = new ArkTSUtils.SendableLruCache<number, number>(); 996pro.put(2, 10); 997pro.get(2); 998pro.get(3); 999console.info(pro.toString()); 1000// Expected output: SendableLruCache[ maxSize = 64, hits = 1, misses = 1, hitRate = 50% ] 1001// maxSize: maximum size of the cache. hits: number of matched queries. misses: number of mismatched queries. hitRate: matching rate. 1002``` 1003 1004### getCapacity<sup>18+</sup> 1005 1006getCapacity(): number 1007 1008Obtains the capacity of this cache. 1009 1010**Atomic service API**: This API can be used in atomic services since API version 18. 1011 1012**System capability**: SystemCapability.Utils.Lang 1013 1014**Return value** 1015 1016| Type | Description | 1017| ------ | ---------------------- | 1018| number | Capacity of the cache.| 1019 1020**Example** 1021 1022```ts 1023let pro = new ArkTSUtils.SendableLruCache<number, number>(); 1024let result = pro.getCapacity(); 1025console.info('result = ' + result); 1026// Expected output: result = 64 1027``` 1028 1029### clear<sup>18+</sup> 1030 1031clear(): void 1032 1033Clears all key-value pairs from this cache. 1034 1035**Atomic service API**: This API can be used in atomic services since API version 18. 1036 1037**System capability**: SystemCapability.Utils.Lang 1038 1039**Example** 1040 1041```ts 1042let pro = new ArkTSUtils.SendableLruCache<number, number>(); 1043pro.put(2, 10); 1044let result = pro.length; 1045pro.clear(); 1046let res = pro.length; 1047console.info('result = ' + result); 1048console.info('res = ' + res); 1049// Expected output: result = 1 1050// Expected output: res = 0 1051``` 1052 1053### getCreateCount<sup>18+</sup> 1054 1055getCreateCount(): number 1056 1057Obtains the number of times that the default internal API is called to create objects. 1058 1059**Atomic service API**: This API can be used in atomic services since API version 18. 1060 1061**System capability**: SystemCapability.Utils.Lang 1062 1063**Return value** 1064 1065| Type | Description | 1066| ------ | -------------------| 1067| number | Number of times that the default internal API is called.| 1068 1069**Example** 1070 1071```ts 1072@Sendable 1073class ChildLRUCache extends ArkTSUtils.SendableLruCache<number, number> { 1074 constructor() { 1075 super(); 1076 } 1077 createDefault(key: number): number { 1078 return key; 1079 } 1080} 1081 1082let lru = new ChildLRUCache(); 1083lru.put(2, 10); 1084lru.get(3); 1085lru.get(5); 1086let res = lru.getCreateCount(); 1087console.info('res = ' + res); 1088// Expected output: res = 2 1089// When the get operation is performed, if the key does not exist, call the createDefault API to check whether the return value is undefined. 1090// If the return value is not undefined, add the key and return value to the cache as a new entry and increase the creation count by one. 1091``` 1092 1093### getMissCount<sup>18+</sup> 1094 1095getMissCount(): number 1096 1097Obtains the number of times that the queried values are mismatched. 1098 1099**Atomic service API**: This API can be used in atomic services since API version 18. 1100 1101**System capability**: SystemCapability.Utils.Lang 1102 1103**Return value** 1104 1105| Type | Description | 1106| ------ | ------------------------ | 1107| number | Number of times that the queried values are mismatched.| 1108 1109**Example** 1110 1111```ts 1112let pro = new ArkTSUtils.SendableLruCache<number, number>(); 1113pro.put(2, 10); 1114pro.get(2); 1115let result = pro.getMissCount(); 1116console.info('result = ' + result); 1117// Expected output: result = 0 1118``` 1119 1120### getRemoveCount<sup>18+</sup> 1121 1122getRemoveCount(): number 1123 1124Obtains the number of times that key-value pairs in the cache are recycled. When the size of the cache exceeds the capacity limit, the least used key-value pairs will be recycled. 1125 1126**Atomic service API**: This API can be used in atomic services since API version 18. 1127 1128**System capability**: SystemCapability.Utils.Lang 1129 1130**Return value** 1131 1132| Type | Description | 1133| ------ | -------------------------- | 1134| number | Number of times that key-value pairs in the cache are recycled.| 1135 1136**Example** 1137 1138```ts 1139let pro = new ArkTSUtils.SendableLruCache<number, number>(); 1140pro.put(2, 10); 1141pro.updateCapacity(2); 1142pro.put(50, 22); 1143let result = pro.getRemoveCount(); 1144console.info('result = ' + result); 1145// Expected output: result = 0 1146``` 1147 1148### getMatchCount<sup>18+</sup> 1149 1150getMatchCount(): number 1151 1152Obtains the number of times that the queried values are matched. 1153 1154**Atomic service API**: This API can be used in atomic services since API version 18. 1155 1156**System capability**: SystemCapability.Utils.Lang 1157 1158**Return value** 1159 1160| Type | Description | 1161| ------ | -------------------------- | 1162| number | Number of times that the queried values are matched.| 1163 1164**Example** 1165 1166```ts 1167let pro = new ArkTSUtils.SendableLruCache<number, number>(); 1168pro.put(2, 10); 1169pro.get(2); 1170let result = pro.getMatchCount(); 1171console.info('result = ' + result); 1172// Expected output: result = 1 1173``` 1174 1175### getPutCount<sup>18+</sup> 1176 1177getPutCount(): number 1178 1179Obtains the number of additions to this cache. 1180 1181**Atomic service API**: This API can be used in atomic services since API version 18. 1182 1183**System capability**: SystemCapability.Utils.Lang 1184 1185**Return value** 1186 1187| Type | Description | 1188| ------ | ---------------------------- | 1189| number | Number of additions to the cache.| 1190 1191**Example** 1192 1193```ts 1194let pro = new ArkTSUtils.SendableLruCache<number, number>(); 1195pro.put(2, 10); 1196let result = pro.getPutCount(); 1197console.info('result = ' + result); 1198// Expected output: result = 1 1199``` 1200 1201### isEmpty<sup>18+</sup> 1202 1203isEmpty(): boolean 1204 1205Checks whether this cache is empty. 1206 1207**Atomic service API**: This API can be used in atomic services since API version 18. 1208 1209**System capability**: SystemCapability.Utils.Lang 1210 1211**Return value** 1212 1213| Type | Description | 1214| ------- | ---------------------------------------- | 1215| boolean | Check result. The value **true** is returned if the cache is empty and does not contain any key-value pairs; otherwise, **false** is returned.| 1216 1217**Example** 1218 1219```ts 1220let pro = new ArkTSUtils.SendableLruCache<number, number>(); 1221pro.put(2, 10); 1222let result = pro.isEmpty(); 1223console.info('result = ' + result); 1224// Expected output: result = false 1225``` 1226 1227### get<sup>18+</sup> 1228 1229get(key: K): V | undefined 1230 1231Obtains the value of a key. 1232 1233**Atomic service API**: This API can be used in atomic services since API version 18. 1234 1235**System capability**: SystemCapability.Utils.Lang 1236 1237**Parameters** 1238 1239| Name| Type| Mandatory| Description | 1240| ------ | ---- | ---- | ------------ | 1241| key | K | Yes | Key based on which the value is queried.| 1242 1243**Return value** 1244 1245| Type | Description | 1246| ------------------------ | ------------------------------------------------------------ | 1247| V \| undefined | If the specified key exists in the cache, the return value is the value associated with that key. If not, the default internal API is called. If the default internal API returns **undefined**, the return value is **undefined**; otherwise, the return value is whatever that API comes up with.| 1248 1249**Example** 1250 1251```ts 1252let pro = new ArkTSUtils.SendableLruCache<number, number>(); 1253pro.put(2, 10); 1254let result = pro.get(2); 1255console.info('result = ' + result); 1256// Expected output: result = 10 1257``` 1258 1259### put<sup>18+</sup> 1260 1261put(key: K,value: V): V 1262 1263Adds a key-value pair to this cache and returns the value associated with the key. If the total number of values in the cache is greater than the specified capacity, the deletion operation is performed. 1264 1265**Atomic service API**: This API can be used in atomic services since API version 18. 1266 1267**System capability**: SystemCapability.Utils.Lang 1268 1269**Parameters** 1270 1271| Name| Type| Mandatory| Description | 1272| ------ | ---- | ---- | -------------------------- | 1273| key | K | Yes | Key of the key-value pair to add. | 1274| value | V | Yes | Value of the key-value pair to add.| 1275 1276**Return value** 1277 1278| Type| Description | 1279| ---- | ------------------------------------------------------------ | 1280| V | Value of the key-value pair added.| 1281 1282**Example** 1283 1284```ts 1285let pro = new ArkTSUtils.SendableLruCache<number, number>(); 1286let result = pro.put(2, 10); 1287console.info('result = ' + result); 1288// Expected output: result = 10 1289``` 1290 1291### values<sup>18+</sup> 1292 1293values(): V[] 1294 1295Obtains all values in this cache, listed from the most to the least recently accessed, where the most recently accessed indicates the key-value pair with the latest operation. 1296 1297**Atomic service API**: This API can be used in atomic services since API version 18. 1298 1299**System capability**: SystemCapability.Utils.Lang 1300 1301**Return value** 1302 1303| Type | Description | 1304| --------- | ------------------------------------------------------------ | 1305| V [] | All values in the cache, listed from the most to the least recently used.| 1306 1307**Example** 1308 1309```ts 1310let pro = new ArkTSUtils.SendableLruCache<number|string,number|string>(); 1311pro.put(2, 10); 1312pro.put(2, "anhu"); 1313pro.put("afaf", "grfb"); 1314let result = pro.values(); 1315console.info('result = ' + result); 1316// Expected output: result = anhu,grfb 1317``` 1318 1319### keys<sup>18+</sup> 1320 1321keys(): K[] 1322 1323Obtains all keys in this cache, listed from the most to the least recently accessed. 1324 1325**Atomic service API**: This API can be used in atomic services since API version 18. 1326 1327**System capability**: SystemCapability.Utils.Lang 1328 1329**Return value** 1330 1331| Type | Description | 1332| --------- | ------------------------------------------------------------ | 1333| K [] | All keys in the cache, listed from the most to the least recently used.| 1334 1335**Example** 1336 1337```ts 1338let pro = new ArkTSUtils.SendableLruCache<number, number>(); 1339pro.put(2, 10); 1340pro.put(3, 1); 1341let result = pro.keys(); 1342console.info('result = ' + result); 1343// Expected output: result = 2,3 1344``` 1345 1346### remove<sup>18+</sup> 1347 1348remove(key: K): V | undefined 1349 1350Removes a key and its associated value from this cache and returns the value associated with the key. If the key does not exist, undefined is returned. 1351 1352**Atomic service API**: This API can be used in atomic services since API version 18. 1353 1354**System capability**: SystemCapability.Utils.Lang 1355 1356**Parameters** 1357 1358| Name| Type| Mandatory| Description | 1359| ------ | ---- | ---- | -------------- | 1360| key | K | Yes | Key to remove.| 1361 1362**Return value** 1363 1364| Type | Description | 1365| ------------------------ | ------------------------------------------------------------ | 1366| V \| undefined | Returns an **Optional** object containing the removed key-value pair if the key exists in the cache; returns undefined if the key does not exist; throws an error if **null** is passed in for **key**.| 1367 1368**Example** 1369 1370```ts 1371let pro = new ArkTSUtils.SendableLruCache<number, number>(); 1372pro.put(2, 10); 1373let result = pro.remove(20); 1374console.info('result = ' + result); 1375// Expected output: result = undefined 1376``` 1377 1378### contains<sup>18+</sup> 1379 1380contains(key: K): boolean 1381 1382Checks whether the cache contains the specified key. 1383 1384**Atomic service API**: This API can be used in atomic services since API version 18. 1385 1386**System capability**: SystemCapability.Utils.Lang 1387 1388**Parameters** 1389 1390| Name| Type | Mandatory| Description | 1391| ------ | ------ | ---- | ---------------- | 1392| key | K | Yes | Key to check.| 1393 1394**Return value** 1395 1396| Type | Description | 1397| ------- | ------------------------------------------ | 1398| boolean | Check result. The value **true** is returned if the cache contains the specified key; otherwise, **false** is returned.| 1399 1400**Example** 1401 1402```ts 1403let pro = new ArkTSUtils.SendableLruCache<number, number>(); 1404pro.put(2, 10); 1405let result = pro.contains(2); 1406console.info('result = ' + result); 1407// Expected output: result = true 1408``` 1409 1410### entries<sup>18+</sup> 1411 1412entries(): IterableIterator<[K,V]> 1413 1414Obtains a new iterator object that contains all key-value pairs in this object. 1415 1416**Atomic service API**: This API can be used in atomic services since API version 18. 1417 1418**System capability**: SystemCapability.Utils.Lang 1419 1420**Return value** 1421 1422| Type | Description | 1423| ----------- | -------------------- | 1424| IterableIterator<[K, V]> | Iterable array.| 1425 1426**Example** 1427 1428```ts 1429let pro = new ArkTSUtils.SendableLruCache<number, number>(); 1430pro.put(2, 10); 1431pro.put(3, 15); 1432let pair:Iterable<Object[]> = pro.entries(); 1433let arrayValue = Array.from(pair); 1434for (let value of arrayValue) { 1435 console.info(value[0]+ ', '+ value[1]); 1436 // Expected output: 1437 // 2, 10 1438 // 3, 15 1439} 1440``` 1441