Category: Proxy usage


Are proxy types thread-safe?


Proxy types are thread-safe under most circumstances, but not all. The reasons for that limitation lie in performance concerns: making every operation thread-safe would have imposed a severe performance penalty on usage of the proxy types. Instead, we chose to make the most commonly problematic and inexpensively securable operations safe and leave the rest to you.

The in-process bindings rely on JNI proxy handles. JNI proxy handles are opaque identifiers representing a Java object. These handles come in different flavors, representing three different types of Java object references: global, weak-global, and local. Virtually all JNI APIs return local references. Local references are therefore the easiest and fastest to use, but they come with a severe usage restriction: they are only usable on on the thread on which they were obtained!

The runtime library normally converts all local object references to global object references so that you don't have to worry about the thread locality restriction. Any proxy object can be used on any application thread. If you just call a method or read an instance field value, the proxy objects are perfectly safe to use concurrently on multiple threads.

The problems start when you are making simultaneous assignments to proxy objects or when you're concurrently accessing shared objects like static String fields. The reasons are that both copy constructors and assignment operators suffer from an internal race condition that could cause the leaking of a JNI handle.

You will just have to guard against such problems by guarding the problematic accesses with mutexes or critical sections.

Remember that the proxy API is only as thread safe as the underlying Java API.


Copyright 2006-2011 by Codemesh, Inc., ALL RIGHTS RESERVED

frequently asked questions
home products support customers partners newsroom about us contact us