1 /*
   2  * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 
  24 /**
  25  * @test
  26  * @bug 6348045 6341887
  27  * @summary GZipOutputStream/InputStream goes critical(calls JNI_Get*Critical)
  28  * and causes slowness.  This test uses Deflater and Inflater directly.
  29  * @key randomness
  30  */
  31 
  32 import java.nio.*;
  33 import java.util.*;
  34 import java.util.zip.*;
  35 
  36 /**
  37  * This test runs Inflater and Defalter in a number of simultaneous threads,
  38  * validating that the deflated & then inflated data matches the original
  39  * data.
  40  */
  41 public class FlaterTest extends Thread {
  42     private static final int DATA_LEN = 1024 * 128;
  43 
  44     private static ByteBuffer dataDirect;
  45     private static ByteBuffer dataHeap;
  46 
  47     // If true, print extra info.
  48     private static final boolean debug = false;
  49 
  50     // Set of Flater threads running.
  51     private static Set<Flater> flaters =
  52         Collections.synchronizedSet(new HashSet<>());
  53 
  54     /** Fill in {@code data} with random values. */
  55     static void createData() {
  56         ByteBuffer bb = ByteBuffer.allocateDirect(DATA_LEN * 8);
  57         for (int i = 0; i < DATA_LEN * 8; i += 8) {
  58             bb.putDouble(i, Math.random());
  59         }
  60         dataDirect = bb;
  61         final ByteBuffer hb = ByteBuffer.allocate(bb.capacity());
  62         hb.duplicate().put(bb.duplicate());
  63         dataHeap = hb;
  64         if (debug) System.out.println("data length is " + bb.capacity());
  65     }
  66 
  67     /** @return the length of the deflated {@code data}. */
  68     private static int getDeflatedLength() {
  69         Deflater deflater = new Deflater();
  70         deflater.setInput(dataDirect.duplicate());
  71         deflater.finish();
  72         byte[] out = new byte[dataDirect.capacity()];
  73         int rc = deflater.deflate(out);
  74         deflater.end();
  75         if (debug) System.out.println("deflatedLength is " + rc);
  76         return rc;
  77     }
  78 
  79     /** Compares given bytes with those in {@code data}.
  80      * @throws Exception if given bytes don't match {@code data}.
  81      */
  82     private static void validate(ByteBuffer buf, int offset, int len) throws Exception {
  83         for (int i = 0; i < len; i++ ) {
  84             if (buf.get(i) != dataDirect.get(offset+i)) {
  85                 throw new Exception("mismatch at " + (offset + i));
  86             }
  87         }
  88     }
  89 
  90     public static void realMain(String[] args) {
  91         int numThreads = args.length > 0 ? Integer.parseInt(args[0]) : 5;
  92         createData();
  93         for (int srcMode = 0; srcMode <= 2; srcMode ++) {
  94             for (int dstMode = 0; dstMode <= 2; dstMode ++) {
  95                 new FlaterTest().go(numThreads, srcMode, dstMode);
  96             }
  97         }
  98     }
  99 
 100     private synchronized void go(int numThreads, int srcMode, int dstMode) {
 101         int deflatedLength = getDeflatedLength();
 102 
 103         long time = System.currentTimeMillis();
 104         for (int i = 0; i < numThreads; i++) {
 105             Flater f = new Flater(deflatedLength, srcMode, dstMode);
 106             flaters.add(f);
 107             f.start();
 108         }
 109         synchronized (flaters) {
 110             while (flaters.size() != 0) {
 111                 try {
 112                     flaters.wait();
 113                 } catch (InterruptedException ex) {
 114                     unexpected(ex);
 115                 }
 116             }
 117         }
 118         time = System.currentTimeMillis() - time;
 119         System.out.println("Time needed for " + numThreads
 120                            + " threads to deflate/inflate: " + time + " ms (srcMode="+srcMode+",dstMode="+dstMode+")");
 121     }
 122 
 123     /** Deflates and inflates data. */
 124     static class Flater extends Thread {
 125         private final int deflatedLength;
 126         private final int srcMode, dstMode;
 127 
 128         private Flater(int length, int srcMode, int dstMode) {
 129             this.deflatedLength = length;
 130             this.srcMode = srcMode;
 131             this.dstMode = dstMode;
 132         }
 133 
 134         /** Deflates and inflates {@code data}. */
 135         public void run() {
 136             if (debug) System.out.println(getName() + " starting run()");
 137             try {
 138                 ByteBuffer deflated = DeflateData(deflatedLength);
 139                 InflateData(deflated);
 140             } catch (Throwable t) {
 141                 t.printStackTrace();
 142                 fail(getName() + " failed");
 143             } finally {
 144                 synchronized (flaters) {
 145                     flaters.remove(this);
 146                     if (flaters.isEmpty()) {
 147                         flaters.notifyAll();
 148                     }
 149                 }
 150             }
 151         }
 152 
 153         /** Returns a copy of {@code data} in deflated form. */
 154         private ByteBuffer DeflateData(int length) {
 155             Deflater deflater = new Deflater();
 156             if (srcMode == 0) {
 157                 deflater.setInput(dataHeap.array());
 158             } else if (srcMode == 1) {
 159                 deflater.setInput(dataHeap.duplicate());
 160             } else {
 161                 assert srcMode == 2;
 162                 deflater.setInput(dataDirect.duplicate());
 163             }
 164             deflater.finish();
 165             ByteBuffer out = dstMode == 2 ? ByteBuffer.allocateDirect(length) : ByteBuffer.allocate(length);
 166             int deflated;
 167             if (dstMode == 0) {
 168                 deflated = deflater.deflate(out.array(), 0, length);
 169                 out.position(deflated);
 170             } else {
 171                 deflater.deflate(out);
 172             }
 173             out.flip();
 174             return out;
 175         }
 176 
 177         /** Inflate a byte array, comparing it with {@code data} during
 178          * inflation.
 179          * @throws Exception if inflated bytes don't match {@code data}.
 180          */
 181         private void InflateData(ByteBuffer bytes) throws Throwable {
 182             Inflater inflater = new Inflater();
 183             if (dstMode == 0) {
 184                 inflater.setInput(bytes.array(), 0, bytes.remaining());
 185             } else {
 186                 inflater.setInput(bytes);
 187             }
 188             if (inflater.getRemaining() == 0) {
 189                 throw new Exception("Nothing to inflate (bytes=" + bytes + ")");
 190             }
 191             int len = 1024 * 8;
 192             int offset = 0;
 193             ByteBuffer buf = srcMode == 2 ? ByteBuffer.allocateDirect(len) : ByteBuffer.allocate(len);
 194             while (inflater.getRemaining() > 0) {
 195                 buf.clear();
 196                 int inflated;
 197                 if (srcMode == 0) {
 198                     inflated = inflater.inflate(buf.array(), 0, buf.remaining());
 199                 } else {
 200                     inflated = inflater.inflate(buf);
 201                 }
 202                 if (inflated == 0) {
 203                     throw new Exception("Nothing inflated (dst=" + buf + ",offset=" + offset + ",rem=" + inflater.getRemaining() + ",srcMode="+srcMode+",dstMode="+dstMode+")");
 204                 }
 205                 validate(buf, offset, inflated);
 206                 offset += inflated;
 207             }
 208         }
 209     }
 210 
 211     //--------------------- Infrastructure ---------------------------
 212     static volatile int passed = 0, failed = 0;
 213     static void pass() {passed++;}
 214     static void fail() {failed++; Thread.dumpStack();}
 215     static void fail(String msg) {System.out.println(msg); fail();}
 216     static void unexpected(Throwable t) {failed++; t.printStackTrace();}
 217     static void check(boolean cond) {if (cond) pass(); else fail();}
 218     static void equal(Object x, Object y) {
 219         if (x == null ? y == null : x.equals(y)) pass();
 220         else fail(x + " not equal to " + y);}
 221     public static void main(String[] args) throws Throwable {
 222         try {realMain(args);} catch (Throwable t) {unexpected(t);}
 223         System.out.println("\nPassed = " + passed + " failed = " + failed);
 224         if (failed > 0) throw new AssertionError("Some tests failed");}
 225 }