or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

async.mdcore.mdindex.mdmetadata.mdprotocols.mdschemes.mdservers.mdtransports.mdutilities.md

index.mddocs/

0

# Apache Thrift Java Library

1

2

Apache Thrift Java Library (libthrift) is a comprehensive RPC framework implementation that enables cross-language communication through efficient data serialization and remote procedure calls. This library provides the core Java runtime components for Thrift, including protocol implementations (binary, compact, JSON), transport mechanisms (socket, HTTP, memory), server types (simple, threaded, non-blocking), and client-side connection management. It supports multiple serialization protocols with automatic code generation from Thrift IDL files, making it ideal for building distributed systems that need to communicate across different programming languages and platforms.

3

4

## Package Information

5

6

- **Package Name**: libthrift

7

- **Package Type**: maven

8

- **Language**: Java

9

- **Group ID**: org.apache.thrift

10

- **Artifact ID**: libthrift

11

- **Installation**: Add to Maven: `<dependency><groupId>org.apache.thrift</groupId><artifactId>libthrift</artifactId><version>0.22.0</version></dependency>`

12

- **Gradle**: `implementation 'org.apache.thrift:libthrift:0.22.0'`

13

14

## Core Imports

15

16

```java

17

import org.apache.thrift.TSerializer;

18

import org.apache.thrift.TDeserializer;

19

import org.apache.thrift.TException;

20

import org.apache.thrift.protocol.TBinaryProtocol;

21

import org.apache.thrift.transport.TSocket;

22

import org.apache.thrift.server.TSimpleServer;

23

```

24

25

## Basic Usage

26

27

### Simple Serialization/Deserialization

28

29

```java

30

import org.apache.thrift.TSerializer;

31

import org.apache.thrift.TDeserializer;

32

import org.apache.thrift.TException;

33

import org.apache.thrift.protocol.TBinaryProtocol;

34

35

// Serialize a Thrift object to bytes

36

TSerializer serializer = new TSerializer(new TBinaryProtocol.Factory());

37

byte[] bytes = serializer.serialize(thriftObject);

38

39

// Deserialize bytes back to a Thrift object

40

TDeserializer deserializer = new TDeserializer(new TBinaryProtocol.Factory());

41

MyThriftObject obj = new MyThriftObject();

42

deserializer.deserialize(obj, bytes);

43

```

44

45

### Simple Client/Server Setup

46

47

```java

48

import org.apache.thrift.transport.TSocket;

49

import org.apache.thrift.transport.TServerSocket;

50

import org.apache.thrift.protocol.TBinaryProtocol;

51

import org.apache.thrift.server.TSimpleServer;

52

53

// Client setup

54

TSocket transport = new TSocket("localhost", 9090);

55

TBinaryProtocol protocol = new TBinaryProtocol(transport);

56

MyService.Client client = new MyService.Client(protocol);

57

transport.open();

58

59

// Server setup

60

TServerSocket serverTransport = new TServerSocket(9090);

61

MyService.Processor<MyServiceHandler> processor = new MyService.Processor<>(new MyServiceHandler());

62

TSimpleServer server = new TSimpleServer(new TSimpleServer.Args(serverTransport).processor(processor));

63

server.serve();

64

```

65

66

## Architecture

67

68

Apache Thrift Java library is built around several key components:

69

70

- **Core Framework**: Base interfaces (`TBase`, `TProcessor`, `TSerializable`) and utilities for object serialization/deserialization

71

- **Protocol Layer**: Multiple protocol implementations (binary, compact, JSON) for data serialization with pluggable protocol factories

72

- **Transport Layer**: Various transport mechanisms (socket, HTTP, memory, file) with layered transport support (framing, compression, SASL)

73

- **Server Framework**: Multiple server implementations (simple, threaded, non-blocking, async) with configurable event handling

74

- **Async Support**: Non-blocking client/server implementations with callback-based async method calls

75

- **Type System**: Complete type support with metadata reflection and partial deserialization capabilities

76

77

## Capabilities

78

79

### Core Framework

80

81

Essential classes and interfaces for Thrift object handling, serialization, and processing.

82

83

```java { .api }

84

// Main serialization utilities

85

public class TSerializer {

86

public TSerializer() throws TTransportException;

87

public TSerializer(TProtocolFactory protocolFactory) throws TTransportException;

88

public byte[] serialize(TBase<?, ?> base) throws TException;

89

public String toString(TBase<?, ?> base) throws TException;

90

}

91

92

public class TDeserializer {

93

public TDeserializer() throws TTransportException;

94

public TDeserializer(TProtocolFactory protocolFactory) throws TTransportException;

95

public void deserialize(TBase base, byte[] bytes) throws TException;

96

public void deserialize(TBase base, String data, String charset) throws TException;

97

}

98

99

// Base interfaces for generated code

100

public interface TBase<T extends TBase<T, F>, F extends TFieldIdEnum> extends Serializable, Cloneable, Comparable<T> {

101

public F fieldForId(int fieldId);

102

public boolean isSet(F field);

103

public Object getFieldValue(F field);

104

public void setFieldValue(F field, Object value);

105

public T deepCopy();

106

public void clear();

107

}

108

109

public interface TProcessor {

110

public void process(TProtocol in, TProtocol out) throws TException;

111

}

112

```

113

114

[Core Framework](./core.md)

115

116

### Protocol Implementations

117

118

Data serialization protocols for different use cases and requirements.

119

120

```java { .api }

121

// Protocol base class and factories

122

public abstract class TProtocol {

123

public abstract void writeMessageBegin(TMessage message) throws TException;

124

public abstract void writeMessageEnd() throws TException;

125

public abstract void writeStructBegin(TStruct struct) throws TException;

126

public abstract void writeStructEnd() throws TException;

127

public abstract void writeFieldBegin(TField field) throws TException;

128

public abstract void writeFieldEnd() throws TException;

129

public abstract void writeFieldStop() throws TException;

130

public abstract void writeBool(boolean b) throws TException;

131

public abstract void writeByte(byte b) throws TException;

132

public abstract void writeI16(short i16) throws TException;

133

public abstract void writeI32(int i32) throws TException;

134

public abstract void writeI64(long i64) throws TException;

135

public abstract void writeDouble(double dub) throws TException;

136

public abstract void writeString(String str) throws TException;

137

public abstract void writeBinary(ByteBuffer bin) throws TException;

138

}

139

140

// Main protocol implementations

141

public class TBinaryProtocol extends TProtocol {

142

public TBinaryProtocol(TTransport trans);

143

public TBinaryProtocol(TTransport trans, boolean strictRead, boolean strictWrite);

144

145

public static class Factory implements TProtocolFactory {

146

public Factory();

147

public Factory(boolean strictRead, boolean strictWrite);

148

}

149

}

150

151

public class TCompactProtocol extends TProtocol {

152

public TCompactProtocol(TTransport transport);

153

154

public static class Factory implements TProtocolFactory {

155

public Factory();

156

}

157

}

158

159

public class TJSONProtocol extends TProtocol {

160

public TJSONProtocol(TTransport trans);

161

162

public static class Factory implements TProtocolFactory {

163

public Factory();

164

}

165

}

166

```

167

168

[Protocol Implementations](./protocols.md)

169

170

### Transport Mechanisms

171

172

Various transport implementations for different communication needs.

173

174

```java { .api }

175

// Transport base classes

176

public abstract class TTransport implements Closeable {

177

public abstract boolean isOpen();

178

public abstract void open() throws TTransportException;

179

public abstract void close();

180

public abstract int read(byte[] buf, int off, int len) throws TTransportException;

181

public abstract void write(byte[] buf, int off, int len) throws TTransportException;

182

public abstract void flush() throws TTransportException;

183

}

184

185

// Main transport implementations

186

public class TSocket extends TEndpointTransport {

187

public TSocket(String host, int port) throws TTransportException;

188

public TSocket(String host, int port, int timeout) throws TTransportException;

189

public void setTimeout(int timeout);

190

}

191

192

public class THttpClient extends TEndpointTransport {

193

public THttpClient(String url) throws TTransportException;

194

public THttpClient(URL url) throws TTransportException;

195

public void setConnectTimeout(int timeout);

196

public void setReadTimeout(int timeout);

197

}

198

199

public class TMemoryBuffer extends TTransport {

200

public TMemoryBuffer(int size);

201

public TMemoryBuffer(byte[] bytes);

202

public byte[] getArray();

203

public int length();

204

}

205

206

// Layered transports

207

public class TFramedTransport extends TLayeredTransport {

208

public TFramedTransport(TTransport transport);

209

public TFramedTransport(TTransport transport, int maxLength);

210

}

211

```

212

213

[Transport Mechanisms](./transports.md)

214

215

### Server Implementations

216

217

Various server types for different performance and scalability requirements.

218

219

```java { .api }

220

// Server base class

221

public abstract class TServer {

222

public abstract void serve();

223

public void stop();

224

public boolean isServing();

225

public void setServerEventHandler(TServerEventHandler eventHandler);

226

227

public static abstract class AbstractServerArgs<T extends AbstractServerArgs<T>> {

228

public T processor(TProcessor processor);

229

public T serverTransport(TServerTransport serverTransport);

230

public T protocolFactory(TProtocolFactory protocolFactory);

231

public T transportFactory(TTransportFactory transportFactory);

232

}

233

}

234

235

// Server implementations

236

public class TSimpleServer extends TServer {

237

public TSimpleServer(AbstractServerArgs args);

238

239

public static class Args extends AbstractServerArgs<Args> {

240

public Args(TServerTransport transport);

241

}

242

}

243

244

public class TThreadPoolServer extends TServer {

245

public TThreadPoolServer(AbstractServerArgs args);

246

247

public static class Args extends AbstractServerArgs<Args> {

248

public Args(TServerTransport transport);

249

public Args executorService(ExecutorService executorService);

250

public Args minWorkerThreads(int n);

251

public Args maxWorkerThreads(int n);

252

}

253

}

254

255

public class TNonblockingServer extends AbstractNonblockingServer {

256

public TNonblockingServer(AbstractNonblockingServerArgs args);

257

258

public static class Args extends AbstractNonblockingServerArgs<Args> {

259

public Args(TNonblockingServerTransport transport);

260

}

261

}

262

```

263

264

[Server Implementations](./servers.md)

265

266

### Asynchronous Operations

267

268

Non-blocking client and server implementations for high-performance applications.

269

270

```java { .api }

271

// Async client base

272

public abstract class TAsyncClient {

273

public TAsyncClient(TProtocolFactory protocolFactory, TAsyncClientManager manager, TNonblockingTransport transport);

274

public TAsyncClient(TProtocolFactory protocolFactory, TAsyncClientManager manager, TNonblockingTransport transport, long timeout);

275

276

public long getTimeout();

277

public void setTimeout(long timeout);

278

public boolean hasError();

279

public Exception getError();

280

}

281

282

// Async client manager

283

public class TAsyncClientManager {

284

public TAsyncClientManager();

285

public TAsyncClientManager(int selectThreadCount, int selectorThreadPoolSize, long timeoutCheckInterval);

286

287

public void call(TAsyncMethodCall method) throws TException;

288

public void stop();

289

}

290

291

// Async method callback

292

public interface AsyncMethodCallback<T> {

293

public void onComplete(T response);

294

public void onError(Exception exception);

295

}

296

297

// Async processor

298

public interface TAsyncProcessor {

299

public void process(AsyncProcessFunction<?, ?, ?> function, TProtocol iproto, TProtocol oproto, AsyncMethodCallback callback) throws TException;

300

}

301

```

302

303

[Asynchronous Operations](./async.md)

304

305

### Serialization Schemes

306

307

Pluggable serialization strategies that control how Thrift objects are encoded and decoded, with support for standard field-based and memory-efficient tuple-based schemes.

308

309

```java { .api }

310

public interface IScheme<T extends TBase> {

311

public void read(TProtocol iproto, T struct) throws TException;

312

public void write(TProtocol oproto, T struct) throws TException;

313

}

314

315

public class StandardScheme<T extends TBase> implements IScheme<T> {

316

// Standard field-by-field serialization with full metadata

317

}

318

319

public class TupleScheme<T extends TBase> implements IScheme<T> {

320

// Memory-efficient tuple serialization without field metadata

321

}

322

```

323

324

[Serialization Schemes](./schemes.md)

325

326

### Metadata and Reflection

327

328

Runtime metadata support for Thrift objects, enabling reflection, introspection, and dynamic handling of structures with field type information and requirements.

329

330

```java { .api }

331

public class FieldMetaData {

332

public final String fieldName;

333

public final byte requirementType;

334

public final FieldValueMetaData valueMetaData;

335

336

public static <T extends TBase<T, F>, F extends TFieldIdEnum> Map<F, FieldMetaData> getStructMetaDataMap(Class<T> sClass);

337

public static <T extends TBase<T, F>, F extends TFieldIdEnum> void addStructMetaDataMap(Class<T> sClass, Map<F, FieldMetaData> map);

338

}

339

340

public class FieldValueMetaData {

341

public final byte type;

342

public final String typedefName;

343

344

public boolean isTypedef();

345

public boolean isBinary();

346

}

347

```

348

349

[Metadata and Reflection](./metadata.md)

350

351

### Utilities and Annotations

352

353

Utility classes and annotations for enhanced Thrift operations, including string processing, partial deserialization support, and field annotations.

354

355

```java { .api }

356

public class StringUtils {

357

public static String toString(Object obj);

358

public static String toBinaryString(byte[] bytes);

359

public static byte[] fastBinaryDecode(String str);

360

public static String fastBinaryEncode(byte[] bytes);

361

}

362

363

@Retention(RetentionPolicy.RUNTIME)

364

@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})

365

public @interface Nullable {

366

String value() default "";

367

}

368

```

369

370

[Utilities and Annotations](./utilities.md)

371

372

## Error Handling

373

374

Apache Thrift provides a hierarchy of exceptions for different error conditions:

375

376

```java { .api }

377

// Base exception

378

public class TException extends Exception {

379

public TException();

380

public TException(String message);

381

public TException(Throwable cause);

382

public TException(String message, Throwable cause);

383

}

384

385

// Application-level exceptions

386

public class TApplicationException extends TException {

387

public static final int UNKNOWN = 0;

388

public static final int UNKNOWN_METHOD = 1;

389

public static final int INVALID_MESSAGE_TYPE = 2;

390

public static final int WRONG_METHOD_NAME = 3;

391

public static final int BAD_SEQUENCE_ID = 4;

392

public static final int MISSING_RESULT = 5;

393

public static final int INTERNAL_ERROR = 6;

394

public static final int PROTOCOL_ERROR = 7;

395

396

public TApplicationException();

397

public TApplicationException(int type);

398

public TApplicationException(int type, String message);

399

public int getType();

400

}

401

```

402

403

## Configuration

404

405

```java { .api }

406

public class TConfiguration {

407

public static final int DEFAULT_MAX_MESSAGE_SIZE = 100 * 1024 * 1024;

408

public static final int DEFAULT_MAX_FRAME_SIZE = 16384000;

409

public static final int DEFAULT_RECURSION_DEPTH = 64;

410

411

public TConfiguration();

412

public TConfiguration(int maxMessageSize, int maxFrameSize, int recursionLimit);

413

414

public int getMaxMessageSize();

415

public void setMaxMessageSize(int maxMessageSize);

416

public int getMaxFrameSize();

417

public void setMaxFrameSize(int maxFrameSize);

418

public int getRecursionLimit();

419

public void setRecursionLimit(int recursionLimit);

420

421

public static Builder custom();

422

}

423

```

424

425

## Common Types

426

427

```java { .api }

428

// Field requirement types

429

public final class TFieldRequirementType {

430

public static final byte REQUIRED = 1;

431

public static final byte OPTIONAL = 2;

432

public static final byte DEFAULT = 3;

433

}

434

435

// Thrift data types

436

public final class TType {

437

public static final byte STOP = 0;

438

public static final byte VOID = 1;

439

public static final byte BOOL = 2;

440

public static final byte BYTE = 3;

441

public static final byte I08 = 3;

442

public static final byte DOUBLE = 4;

443

public static final byte I16 = 6;

444

public static final byte I32 = 8;

445

public static final byte I64 = 10;

446

public static final byte STRING = 11;

447

public static final byte UTF7 = 11;

448

public static final byte STRUCT = 12;

449

public static final byte MAP = 13;

450

public static final byte SET = 14;

451

public static final byte LIST = 15;

452

public static final byte UTF8 = 16;

453

public static final byte UTF16 = 17;

454

public static final byte UUID = 18;

455

}

456

457

// Message types

458

public final class TMessageType {

459

public static final byte CALL = 1;

460

public static final byte REPLY = 2;

461

public static final byte EXCEPTION = 3;

462

public static final byte ONEWAY = 4;

463

}

464

```