public void testEncryption(
      StreamingAead stream, byte[] associatedData, int chunkSize, int numberOfChunks)
      throws Exception {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    WritableByteChannel encChannel =
        stream.newEncryptingChannel(Channels.newChannel(bos), associatedData);
    int numberOfThreads = 10;
    Thread[] thread = new Thread[numberOfThreads];
    ExceptionHandler exceptionHandler = new ExceptionHandler();
    for (int i = 0; i < numberOfThreads; i++) {
      thread[i] = new EncryptingThread(encChannel, chunkSize, numberOfChunks, (byte) i);
      thread[i].setUncaughtExceptionHandler(exceptionHandler);
    }
    for (int i = 0; i < numberOfThreads; i++) {
      thread[i].start();
    }
    for (int i = 0; i < numberOfThreads; i++) {
      thread[i].join();
    }
    exceptionHandler.check();
    encChannel.close();
    byte[] ciphertext = bos.toByteArray();
    ReadableByteChannel ctChannel = new ByteBufferChannel(ciphertext);
    ReadableByteChannel ptChannel = stream.newDecryptingChannel(ctChannel, associatedData);
    ByteBuffer decrypted = ByteBuffer.allocate(numberOfThreads * chunkSize * numberOfChunks + 1);
    ptChannel.read(decrypted);

    // Test whether the writing the chunks was done in an atomic manner.
    byte[] plaintext = decrypted.array();
    for (int i = 0; i < numberOfThreads * numberOfChunks; i++) {
      for (int j = 0; j < chunkSize - 1; j++) {
        int idx = i * chunkSize + j;
        if (plaintext[idx] != plaintext[idx + 1]) {
          int thread1 = plaintext[idx] & 0xff;
          int thread2 = plaintext[idx + 1] & 0xff;
          fail("Chunk " + i + " contains bytes from thread " + thread1 + " and " + thread2 + ".");
        }
      }
    }
  }
Test for thread safety. This test is an incorrect use case for StreamingAead implementations.
Streams have state and hence their behaviour is not well defined. Nevertheless if an encrypting
channel is used concurrently we expect the following behaviour: (1) The resulting ciphertext
has valid format. (2) All plaintext is encrypted. (3) The thread sanitizer does not find
anything.
java_src/src/test/java/com/google/crypto/tink/subtle/StreamingAeadThreadSafetyTest.java