Ejemplo n.º 1
0
    /**
     * @param time Test time.
     * @param writers Number of writers threads.
     * @throws Exception If failed.
     */
    public void testQueue(long time, int writers) throws Exception {
      System.out.println("Start test [writers=" + writers + ", time=" + time + "]");

      Thread rdr =
          new Thread() {
            @SuppressWarnings({"InfiniteLoopStatement", "unchecked"})
            @Override
            public void run() {
              try {
                while (true) {
                  Future fut;

                  while ((fut = queue.poll()) != null) {
                    qSize.decrementAndGet();

                    fut.onDone(true);
                  }

                  long size = qSize.get();

                  if (size == 0) {
                    synchronized (mux) {
                      while (queue.isEmpty()) {
                        mux.wait();
                      }
                    }
                  }
                }
              } catch (InterruptedException ignore) {
              }
            }
          };

      rdr.start();

      List<Thread> putThreads = new ArrayList<>();

      for (int i = 0; i < writers; i++) {
        putThreads.add(
            new Thread() {
              @SuppressWarnings("CallToNotifyInsteadOfNotifyAll")
              @Override
              public void run() {
                try {
                  while (!stop) {
                    long id = cnt.incrementAndGet();

                    Future<Boolean> fut = new Future<Boolean>(new Message(id));

                    queue.offer(fut);

                    long size = qSize.incrementAndGet();

                    if (size == 1) {
                      synchronized (mux) {
                        mux.notify();
                      }
                    }

                    Boolean res = fut.get();

                    if (!res) {
                      System.out.println("Error");
                    }
                  }
                } catch (Exception e) {
                  e.printStackTrace();
                }
              }
            });
      }

      for (Thread t : putThreads) t.start();

      Thread.sleep(time);

      stop = true;

      for (Thread t : putThreads) t.join();

      rdr.interrupt();

      rdr.join();

      System.out.println("Total: " + cnt.get());

      System.gc();
      System.gc();
      System.gc();
    }