1# Using HiCollie (C/C++)
2
3HiCollie provides APIs for detecting service thread stuck and jank events and reporting stuck events.
4
5## Available APIs
6| API                         | Description                             |
7| ------------------------------- | --------------------------------- |
8| OH_HiCollie_Init_StuckDetection | Registers a callback to periodically detect service thread stuck events.           |
9| OH_HiCollie_Init_JankDetection | Registers a callback to detect service thread jank events. To monitor thread jank events, you should implement two callbacks as instrumentation functions, placing them before and after the service thread processing event.                  |
10| OH_HiCollie_Report | Reports service thread stuck events and generates timeout logs to help locate application timeout events. This API is used together with **OH_HiCollie_Init_StuckDetection()**, which initializes the stuck event detection at first, and then **OH_HiCollie_Report()** reports the stuck event when it occurs.|
11
12> **NOTE**
13>
14> The service thread stuck faultlog starts with **appfreeze-** and is generated in **Device/data/log/faultlog/faultlogger/**. The log files are named in the format of **appfreeze-application bundle name-application UID-time (seconds)**. For details, see [appfreeze Log Analysis](./appfreeze-guidelines.md#appfreeze-log-analysis).
15>
16> For details about the specifications of service thread jank logs, see [Main Thread Jank Event Specifications](./hiappevent-watcher-mainthreadjank-events-arkts.md#main-thread-jank-event-specifications).
17
18
19For details (such as parameter usage and value ranges), see [HiCollie](../reference/apis-performance-analysis-kit/_hi_hicollie.md).
20
21## How to Develop
22The following describes how to add a button in the application and click the button to call the HiCollie APIs.
23
241. Create a native C++ project and import the **jsoncpp** file to the project. The directory structure is as follows:
25
26   ```yml
27   entry:
28     src:
29       main:
30         cpp:
31           - types:
32               libentry:
33                 - index.d.ts
34           - CMakeLists.txt
35           - napi_init.cpp
36         ets:
37           - entryability:
38               - EntryAbility.ts
39           - pages:
40               - Index.ets
41   ```
42
432. In the **CMakeLists.txt** file, add the source file and dynamic libraries.
44
45   ```cmake
46   # Add libhilog_ndk.z.so (log output).
47   target_link_libraries(entry PUBLIC libace_napi.z.so libhilog_ndk.z.so libohhicollie.so)
48   ```
49
503. Import the dependencies to the **napi_init.cpp** file, and define **LOG_TAG** and the test method.
51
52   ```c++
53    #include "napi/native_api.h"
54    #include "hilog/log.h"
55    #include "hicollie/hicollie.h"
56    #include <thread>
57    #include <string>
58    #include <unistd.h>
59    #include <atomic>
60
61    #undef LOG_TAG
62    #define LOG_TAG "testTag"
63
64    static OH_HiCollie_BeginFunc beginFunc_; // Define the callback object used before the processing event.
65    static OH_HiCollie_EndFunc endFunc_; // Define the callback object used after the processing event.
66    HiCollie_DetectionParam param {.sampleStackTriggerTime = 150, .reserved = 0}; // Define a struct.
67    int64_t lastWatchTime = 0; // Record the last detection time.
68    const int64_t CHECK_INTERNAL_TIME = 3000; // Set the detection interval.
69    std::shared_ptr<std::atomic<bool>> isReport = std::make_shared<std::atomic<bool>>(false); // Set the flag for reporting stuck events.
70    int count = 0; // Record the first initialization.
71    bool needReport = false; // Set whether to report the stuck events.
72
73    // Define the callback.
74    void InitBeginFunc(const char* eventName)
75    {
76        std::string str(eventName);
77        OH_LOG_INFO(LogType::LOG_APP, "InitBeginFunc eventName: %{public}s", str.c_str());
78    }
79    void InitEndFunc(const char* eventName)
80    {
81        std::string str(eventName);
82        OH_LOG_INFO(LogType::LOG_APP, "OH_HiCollie_EndFunc eventName: %{public}s", str.c_str());
83    }
84    // Define the callback of the subthread.
85    void TestJankDetection()
86    {
87        beginFunc_ = InitBeginFunc; // Initialize the callback.
88        endFunc_ = InitEndFunc;
89        int initResult = OH_HiCollie_Init_JankDetection(&beginFunc_, &endFunc_, param); // Initialize the function for detecting thread jank events.
90        OH_LOG_INFO(LogType::LOG_APP, "OH_HiCollie_Init_JankDetection: %{public}d", initResult); // Display the success result 0.
91        int count = 0;
92        while (count < 2) {
93            beginFunc_("TestBegin"); // Set the callback used to record the start time of the processing event.
94            usleep(350 * 1000); // Simulate a thread jank event by putting the thread to sleep for 350 ms.
95            endFunc_("TestEnd"); // Set the callback used to record the end time of the processing event.
96            count++;
97        }
98    }
99
100    static napi_value TestHiCollieJankNdk(napi_env env, napi_callback_info info)
101    {
102        std::thread threadObj(TestJankDetection); // Create a subthread.
103        threadObj.join(); // Execute the callback.
104        return 0;
105    }
106
107    int64_t GetCurrentTime()
108    {
109      return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::
110          system_clock::now().time_since_epoch()).count();
111    }
112
113    bool ReportEvent()
114    {
115      if ((GetCurrentTime() - lastWatchTime) > CHECK_INTERNAL_TIME) {
116          return true;
117      }
118      return false;
119    }
120
121    void TestTask()
122    {
123        if (needReport && ReportEvent()) {
124          bool temp = isReport->load();
125          int reportResult = OH_HiCollie_Report(&temp);
126          OH_LOG_INFO(LogType::LOG_APP, "OH_HiCollie_Report: %{public}d", reportResult); // Display the success result 0.
127          OH_LOG_INFO(LogType::LOG_APP, "OH_HiCollie_Report isReport: %{public}d", temp);
128          needReport = false;
129        }
130        int64_t now = GetCurrentTime();
131        if ((now - lastWatchTime) >= (CHECK_INTERNAL_TIME / 2)) {
132            lastWatchTime = now;
133        }
134    }
135
136    // Define the callback of the subthread.
137    void TestStuckDetection()
138    {
139        int initResult = -1;
140        if(count == 0) {
141          initResult = OH_HiCollie_Init_StuckDetection(TestTask); // Initialize the function for detecting thread stuck events.
142          OH_LOG_INFO(LogType::LOG_APP, "OH_HiCollie_Init_StuckDetection: %{public}d", initResult); // Display the success result 0.
143          count++;
144        }
145    }
146    static napi_value TestHiCollieStuckNdk(napi_env env, napi_callback_info info)
147    {
148      std::thread threadObj(TestStuckDetection); // Create a subthread.
149      threadObj.join(); // Execute the callback.
150      return 0;
151    }
152   ```
153
1544. Register **TestHiCollieNdk** as an ArkTS API.
155
156   In the **napi_init.cpp** file, register **TestHiCollieNdk** as an ArkTS API.
157
158   ```c++
159    static napi_value Init(napi_env env, napi_value exports)
160    {
161        napi_property_descriptor desc[] = {
162            { "testHiCollieJankNdk", nullptr, TestHiCollieJankNdk, nullptr, nullptr, nullptr, napi_default, nullptr },
163            { "testHiCollieStuckNdk", nullptr, TestHiCollieStuckNdk, nullptr, nullptr, nullptr, napi_default, nullptr }};
164        };
165        napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
166        return exports;
167    }
168   ```
169
170   In the **index.d.ts** file, define the ArkTS API.
171
172   ```typescript
173   export const testHiCollieJankNdk: () => void;
174   export const testHiCollieStuckNdk: () => void;
175   ```
176
1775. Edit the **Index.ets** file.
178
179   ```ts
180   import testNapi from 'libentry.so'
181
182   @Entry
183   @Component
184   struct Index {
185     @State message: string = 'Hello World'
186
187     build() {
188       Row() {
189         Column() {
190           Button("testHiCollieJankNdk")
191             .fontSize(50)
192             .fontWeight(FontWeight.Bold)
193             .onClick(testNapi.testHiCollieJankNdk);// Add a click event to trigger testHiCollieJankNdk().
194           Button("testHiCollieStuckNdk")
195             .fontSize(50)
196             .fontWeight(FontWeight.Bold)
197             .onClick(testNapi.testHiCollieStuckNdk);// Add a click event to trigger testHiCollieStuckNdk().
198         }
199         .width('100%')
200       }
201       .height('100%')
202     }
203   }
204   ```
205
2066. Click the **Run** button in DevEco Studio to run the project.
207
2087. At the bottom of DevEco Studio, switch to the **Log** tab and set the filter criteria to **testTag**.
209
210    (1) Wait for 10s and click the **testHiCollieJankNdk** button. (The jank event detection is not performed within 10s after the thread starts.)
211      The thread timeout information of the sampling stack obtained through **OH_HiCollie_Init_JankDetection()** is displayed in **/data/app/el2/100/log/application bundle name/watchdog/BUSSINESS_THREAD_JANK_XXX.txt.**
212
213(2) Click the **testHiCollieStuckNdk** button.
214      The callback used for detecting stuck events is initialized through **OH_HiCollie_Init_StuckDetection()**. You can define the detection function for stuck events as required.
215