# @rocicorp/lock

> Implements Lock and RWLock synchronization primitives.

Latest version **2.0.1** (published 2026-05-24) · Apache-2.0 license · 0 weekly downloads

## Install

```sh
npm install @rocicorp/lock
pnpm add @rocicorp/lock
yarn add @rocicorp/lock
bun add @rocicorp/lock
```

## Health

**Score 65/100 (B)** — status: active.

Positive: has types; esm support; no vulnerabilities; has provenance; high quality score.

Warnings: low downloads.

## Facts

| | |
|---|---|
| Version | 2.0.1 |
| Published | 2026-05-24 |
| First published | 2022-03-17 |
| Weekly downloads | 0 |
| License | Apache-2.0 |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Node | >=22.0.0 |
| Dependencies | 0 |
| Unpacked size | 15 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Provenance | attested (GitHub Actions) |
| Maintainers | arv, aboodman, cesaraz1, grgbkr, 0xcadams, tantaman, darick |

## Links

- npm: https://www.npmjs.com/package/@rocicorp/lock
- Repository: github:rocicorp/lock
- npm.io page: https://npm.io/package/@rocicorp/lock

## Recent versions

- 2.0.1 (latest) — 2026-05-24
- 2.0.0 — 2026-05-24
- 1.0.4 — 2024-06-03
- 1.0.3 — 2023-09-12
- 1.0.2 — 2023-09-12
- 1.0.1 — 2022-03-17
- 1.0.0 — 2022-03-17

## README

# Lock

Provides `Lock` and `RWLock` (read write lock) synchronization primitives for
protecting in-memory state across multiple tasks and/or microtasks.

# Installation

```
npm install @rocicorp/lock
```

# Usage

`Lock` is a mutex that can be used to synchronize access to a shared resource.

```ts
import {Lock} from '@rocicorp/lock';

const lock = new Lock();

async function f(n) {
  const v = await lock.withLock(async () => {
    await sleep(1000);
    return n;
  });
  console.log(n);
}

void f(1);
void f(2);
// prints 1 at t=1000
// prints 2 at t=2000
```

`RWLock` is a read write lock. There can be mutlipe readers at the same time but only one writer at the same time.

```js
import {RWLock} from '@rocicorp/lock';

const rwLock = new RWLock();

async function read(n) {
  const v = await lock.withRead(async () => {
    await sleep(1000);
    return n;
  });
  console.log('read', n);
}

async function write(n) {
  const v = await lock.withWrite(async () => {
    await sleep(1000);
    return n;
  });
  console.log('write', n);
}

void read(1);
void write(2);
void read(3);
// prints read 1 at t=1000
// prints read 3 at t=1000
// prints write 2 at t=2000
```

Both `Lock` and `RWLock` expose non "with" methods (`lock`, `read` and `write`). These returns a promise to a release function that resolves when the lock is acquired. This is useful when you cannot wrap your code in a function like the examples above. When using these For example:

```js
const lock = new Lock();

const release = await lock.lock();
// here we got the lock
// do something
release();
```

---
_Source: https://npm.io/package/@rocicorp/lock · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
