> For the complete documentation index, see [llms.txt](https://docs.apryse.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.apryse.com/web/full-api/advanced-features.md).

# Advanced features of Full API

Learn how to set up a full API project with advanced control features like locking and memory management. Optimize performance using WebAssembly Threads and Emscripten backends. Explore Full API locki

To get started with setting up a full API project, refer to the [getting starting guide](/web/full-api/full-api-overview.md).

The full API contains several methods for more advanced control over its processes via locking and memory management. This guide will provide an explanation of how to use these features and will also shed some light on the backend processes of the full API.

## Understanding Full API backends

For optimal performance, the full API uses two different backends to run its processes, WebAssembly Threads and Emscripten.

* WebAssembly Threads has better performance, since it supports multithreading but currently is only supported on Google Chrome for Desktop. This may change in the future.
* Emscripten (which compiles both non-threaded WebAssembly and asm.js implementations) starts up a little faster and is compatible with most browsers, but has slower runtime performance.

On Google Chrome the WebAssembly Threads backend will be used by default, while other browsers will use the Emscripten backend.

## Full API locking

Locking prevents multiple simultaneous accesses to a PDF document in a Full API process so that it cannot be changed by outside operations.

An Apryse SDK lock is based on two principles:

[Reentrant mutex (also known as recursive lock)](https://en.wikipedia.org/wiki/Reentrant_mutex) Recursive mutex may be locked multiple times by the same process/thread without causing a deadlock.

[Readers-writer (RW) lock (also known as shared-exclusive lock)](https://en.wikipedia.org/wiki/Readers-writer_lock) An RW lock allows concurrent access for read-only operations, while write operations require exclusive access.

Full API contains three main types of locking and unlocking statements:

### Lock and unlock

Locks a PDF document to prevent competing threads from accessing the document at the same time. Threads attempting to access the document will wait in suspended state until the thread that owns the lock calls `doc.Unlock()`.

* `[PDFDoc].lock()`
* `[PDFDoc].unlock()` -

### Auto unlock

Documents are automatically unlocked upon process completion if the user code is being using `PDFNet.runWithCleanup()`.

* `PDFNet.runWithCleanup()`

### LockRead and unlockRead

Locks the document to prevent competing write threads (using lock()) from accessing the document at the same time. Read-only threads however, will be allowed to access the document.

* `[PDFDoc].lockRead()`
* `[PDFDoc].unlockRead()`

Threads attempting to obtain write access to the document will wait in suspended state until the thread that owns the lock calls `doc.unlockRead()`. Documents are automatically unlocked upon process completion if the user code is being run with `PDFNet.runWithCleanup()`.

{% hint style="warning" %}
**Note**

Obtaining a write lock while holding a read lock is not permitted and will throw an exception. If this situation is encountered please either unlock the read lock before the write lock is obtained or acquire a write lock (rather than read lock) in the first place.
{% endhint %}

### Manual document locking example

{% tabs %}
{% tab title="JavaScript" %}
{% code lineNumbers="true" %}

```js
async function main() {
  try {
    const doc = await PDFNet.PDFDoc.create();
    doc.initSecurityHandler();
    // documents require locking
    doc.lock();
    // do stuff with document
  } catch (err){
    console.log(err);
  } finally {
    // unlocks the document
    await doc.unlock();
  }
}
PDFNet.runWithoutCleanup(main);
// if you use PDFNet.runWithCleanup(main), no need to unlock
```

{% endcode %}
{% endtab %}
{% endtabs %}

[PDFDoc.create](https://sdk.apryse.com/api/web/Core.PDFNet.PDFDoc.html#.create__anchor) [PDFDoc.initSecurityHandler](https://sdk.apryse.com/api/web/Core.PDFNet.PDFDoc.html#initSecurityHandler__anchor) [PDFDoc.lock](https://sdk.apryse.com/api/web/Core.PDFNet.PDFDoc.html#lock__anchor) [PDFDoc.unlock](https://sdk.apryse.com/api/web/Core.PDFNet.PDFDoc.html#unlock__anchor) [PDFNet.runWithoutCleanup](https://sdk.apryse.com/api/web/Core.PDFNet.html#.runWithoutCleanup__anchor)

### BeginOperation and finishOperation

`beginOperation()` locks all worker operations on PDFNet.

* `PDFNet.beginOperation()`
* `PDFNet.finishOperation()`

### RunWithCleanup and runWithoutCleanup

Both `PDFNet.runWithCleanup()` and `PDFNet.runWithoutCleanup()` call `beginOperation()` and end with `finishOperation()`, so `beginOperation()` and `finishOperation()` should only be used when PDFNet needs to be unlocked in the middle of a process.

* `PDFNet.runWithCleanup()`
* `PDFNet.runWithoutCleanup()`

{% tabs %}
{% tab title="JavaScript" %}
{% code lineNumbers="true" %}

```js
async function main() {
  // ...
}
// Automatically locks all worker operations
PDFNet.runWithCleanup(main);
```

{% endcode %}
{% endtab %}
{% endtabs %}

[PDFNet.runWithCleanup](https://sdk.apryse.com/api/web/Core.PDFNet.html#.runWithCleanup__anchor)

### Queue operations

Running multiple unrelated full API operations simultaneously may result in race conditions. This can be resolved by synchronizing the full API operations using a queue. The deck.js sample demonstrates this by queuing its renderPage calls to prevent race conditions on its single shared PDFDraw object.

For this reason, calling `beginOperation()` a second time before `finishOperation()` is called will cause an exception to be thrown.

There are some cases where unlocking in the middle of a full API process may be required. This usually happens if `requirePage()` needs to be called on a document.

The ViewerEdit sample on the [samples page](/web/get-started/guides/samples/full-apis.md) shows a situation where manual unlocking and re-locking may be used.

{% tabs %}
{% tab title="JavaScript" %}
{% code lineNumbers="true" %}

```js
const doc = await PDFNet.PDFDoc.create();
doc.initSecurityHandler();
doc.lock();
// ...

// This section is only required to ensure the page is available
// for incremental download. At the moment the call to requirePage must be
// wrapped in this manner to avoid potential deadlocks and
// allow other parts of the viewer to run while the page is being downloaded.
doc.unlock();
await PDFNet.finishOperation();
// requirePage(pageNum) ensures that the first page is downloaded before it is accessed.
await doc.requirePage(1);
await PDFNet.beginOperation();
doc.lock();
```

{% endcode %}
{% endtab %}
{% endtabs %}

[PDFDoc.create](https://sdk.apryse.com/api/web/Core.PDFNet.PDFDoc.html#.create__anchor) [PDFDoc.initSecurityHandler](https://sdk.apryse.com/api/web/Core.PDFNet.PDFDoc.html#initSecurityHandler__anchor) [PDFDoc.lock](https://sdk.apryse.com/api/web/Core.PDFNet.PDFDoc.html#lock__anchor) [PDFDoc.unlock](https://sdk.apryse.com/api/web/Core.PDFNet.PDFDoc.html#unlock__anchor) [PDFDoc.requirePage](https://sdk.apryse.com/api/web/Core.PDFNet.PDFDoc.html#requirePage__anchor) [PDFNet.beginOperation](https://sdk.apryse.com/api/web/Core.PDFNet.html#.beginOperation__anchor) [PDFNet.finishOperation](https://sdk.apryse.com/api/web/Core.PDFNet.html#.finishOperation__anchor)

## Memory management

The full API automatically cleans up all objects in a process initialized using `PDFNet.runWithCleanup()` once the process has finished running. In almost all cases it is recommended to use this function to avoid memory leaks and complicated memory management.

### Retain objects

In some situations you may wish to retain an object after the process has finished. A common example of this would be to create a document and retain it after processing. The ViewerPreprocess sample on the [samples page](/web/get-started/guides/samples/full-apis.md) has an example of how this can be done.

* `[Obj].takeOwnership()`

For most use cases using `PDFNet.runWithCleanup()` and `[Obj].takeOwnership()` is sufficient. However, there are additional ways to manage memory:

### Deallocate objects

Deallocates individual objects. Only objects that derive from PDFNet.Destroyable have this method.

* `[Obj].destroy()`

### Deallocate stack

Stack-based deallocation. Calling `endDeallocateStack()` will deallocate all objects that were created since the last call to `PDFNet.startDeallocateStack()`.

* `PDFNet.startDeallocateStack()`
* `PDFNet.endDeallocateStack()`

In general, stack-based deallocation is recommended because it is easier to manage for larger sections of code.

### More examples

Example of default/automatic deallocation:

{% tabs %}
{% tab title="JavaScript" %}
{% code lineNumbers="true" %}

```js
async function main() {
  try {
    // documents require deallocation
    const doc = await PDFNet.PDFDoc.create();
    // object that requires deallocation
    const page_iter = await doc.getPageIterator();
    // object that requires deallocation
    const writer = await PDFNet.ElementWriter.create();
  } catch (err){
    console.log(err);
  }
}

// deallocates all objects once main finishes running
PDFNet.runWithCleanup(main);
```

{% endcode %}
{% endtab %}
{% endtabs %}

[PDFDoc.create](https://sdk.apryse.com/api/web/Core.PDFNet.PDFDoc.html#.create__anchor) [PDFDoc.getPageIterator](https://sdk.apryse.com/api/web/Core.PDFNet.PDFDoc.html#getPageIterator__anchor) [ElementWriter.create](https://sdk.apryse.com/api/web/Core.PDFNet.ElementWriter.html#.create__anchor)

Example of individual deallocation:

{% tabs %}
{% tab title="JavaScript" %}
{% code lineNumbers="true" %}

```js
async function main() {
  try {
    const doc = await PDFNet.PDFDoc.create();
    const page_iter = await doc.getPageIterator();
    const writer = await PDFNet.ElementWriter.create();
  } catch (err){
    console.log(err);
  } finally {
    await doc.destroy();
    await page_iter.destroy();
    await writer.destroy();
  }
}
PDFNet.runWithoutCleanup(main);
```

{% endcode %}
{% endtab %}
{% endtabs %}

[PDFDoc.create](https://sdk.apryse.com/api/web/Core.PDFNet.PDFDoc.html#.create__anchor) [PDFDoc.getPageIterator](https://sdk.apryse.com/api/web/Core.PDFNet.PDFDoc.html#getPageIterator__anchor) [PDFDoc.destroy](https://sdk.apryse.com/api/web/Core.PDFNet.PDFDoc.html#destroy__anchor) [ElementWriter.create](https://sdk.apryse.com/api/web/Core.PDFNet.ElementWriter.html#.create__anchor) [ElementWriter.destroy](https://sdk.apryse.com/api/web/Core.PDFNet.ElementWriter.html#destroy__anchor) [Iterator.destroy](https://sdk.apryse.com/api/web/Core.PDFNet.Iterator.html#destroy__anchor) [PDFNet.runWithoutCleanup](https://sdk.apryse.com/api/web/Core.PDFNet.html#.runWithoutCleanup__anchor)

Example of stack-based deallocation:

{% tabs %}
{% tab title="JavaScript" %}
{% code lineNumbers="true" %}

```js
async function main() {
  try {
    await PDFNet.startDeallocateStack();
    const doc = await PDFNet.PDFDoc.create();
    const page_iter = await doc.getPageIterator();
    const writer = await PDFNet.ElementWriter.create();
    await PDFNet.endDeallocateStack();
  } catch (err){
    console.log(err);
  }
}
PDFNet.runWithoutCleanup(main);
```

{% endcode %}
{% endtab %}
{% endtabs %}

[PDFNet.startDeallocateStack](https://sdk.apryse.com/api/web/Core.PDFNet.html#.startDeallocateStack__anchor) [PDFNet.endDeallocateStack](https://sdk.apryse.com/api/web/Core.PDFNet.html#.endDeallocateStack__anchor) [PDFDoc.create](https://sdk.apryse.com/api/web/Core.PDFNet.PDFDoc.html#.create__anchor) [PDFDoc.getPageIterator](https://sdk.apryse.com/api/web/Core.PDFNet.PDFDoc.html#getPageIterator__anchor) [ElementWriter.create](https://sdk.apryse.com/api/web/Core.PDFNet.ElementWriter.html#.create__anchor) [PDFNet.runWithoutCleanup](https://sdk.apryse.com/api/web/Core.PDFNet.html#.runWithoutCleanup__anchor)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.apryse.com/web/full-api/advanced-features.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
