Search code examples
javahadoopjava-native-interfacenative

What is clazz used for in "private static Class clazz = SnappyDecompressor.class" source file?


I am studying the compressor implementation (in Java) for Snappy, Zlib and others. Near the top of the source file is this line below. Can anyone explain to me what it means?

HACK - Use this as a global lock in the JNI layer
@SuppressWarnings({"unchecked", "unused"})
private static Class clazz = SnappyDecompressor.class;

I understand, for example, in Snappy, SnappyDecompressor.java is essentially a wrapper for snappy C / native implementation, and to make calls to that C implementation, the Java layer makes calls through JNI interface.

The top part of the source for snappy (Java wrapper), SnappyDecompressor.java is here:

package org.apache.hadoop.io.compress.snappy;
import java.io.IOException;
import java.nio.Buffer;
import java.nio.ByteBuffer;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.io.compress.Decompressor;

/**
 * A {@link Decompressor} based on the snappy compression algorithm.
 * http://code.google.com/p/snappy/
 */
public class SnappyDecompressor implements Decompressor {
  private static final Log LOG =
      LogFactory.getLog(SnappyCompressor.class.getName());
  private static final int DEFAULT_DIRECT_BUFFER_SIZE = 64 * 1024;

  // HACK - Use this as a global lock in the JNI layer
  @SuppressWarnings({"unchecked", "unused"})
  private static Class clazz = SnappyDecompressor.class;

Full source


Solution

  • As indicated in the comment: it is used from the JNI layer, seemingly for some locking from the JNI layer. (see the full Decompressor source)

    Lines 76, 77:

    SnappyDecompressor_clazz = (*env)->GetStaticFieldID(env, clazz, "clazz",
                                                     "Ljava/lang/Class;");
    

    Line 83:

    jobject clazz = (*env)->GetStaticObjectField(env,thisj, SnappyDecompressor_clazz);
    

    Lines 100 to 102:

    LOCK_CLASS(env, clazz, "SnappyDecompressor");
    const char* compressed_bytes = (const char*)(*env)->GetDirectBufferAddress(env, compressed_direct_buf);
    UNLOCK_CLASS(env, clazz, "SnappyDecompressor");