/** Method that gets invoked by the worker {@link Thread} */
  protected void run() {
    Entry entry;

    while (keepRunning()) {
      synchronized (entries) {
        entry = entries.poll();

        if (entry == null) {
          try {
            entries.notify(); // notify potential flush
            entries.wait(); // wait for more work
          } catch (InterruptedException ie) {
            logger.log(
                Level.WARNING,
                "Got interrupted, may cause performance issues, " + worker.getName(),
                ie);
          }

          // try again
          continue;
        }
      }

      // there is work!
      process(entry);
    }
  }
Esempio n. 2
0
  /**
   * Run Method which simulates the number of threads running on the bridge
   *
   * @param None
   * @return None
   */
  public void run() {
    while (true) {
      Truck theTruck; // Stores the Truck Object

      // synchronized on truck queue before removing the truck objects
      synchronized (theTruckQueue) {
        // If there are no Trucks then wait for trucks to arrive
        while (theTruckQueue.isEmpty()) {
          try {
            theTruckQueue.wait();
          } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        }
        theTruck = theTruckQueue.remove();
      }
      // Check for the maximum trucks allowed on the bridge and max weight
      // allowed on the bridge
      // Do not allow any more trucks if we exceed any of the limit
      while (theBridgeQueue.size() == MAX_SIZE
          || (theTruck.getWeight() + getTotalWeight()) >= MAX_WEIGHT) {
        System.out.println("Total number of trucks on Bridge: " + theBridgeQueue.size());
        System.out.println("Total Weight on Bridge is: " + getTotalWeight());
        Truck truckOnBridge = theBridgeQueue.remove();
        System.out.println("The truck Entered " + truckOnBridge.getSide() + " of the Bridge left");
      }

      // Allow the trucks on the bridge on first come first serve basis
      System.out.println("Truck " + theTruck.getSide() + " is Entering the Bridge");
      theBridgeQueue.add(theTruck);
      System.out.println("Truck " + theTruck.getSide() + " is running on the Bridge");
    }
  }
Esempio n. 3
0
  public void write(ByteBuffer src, boolean sync) {
    if (this.selectionKey == null || !this.selectionKey.isValid()) return;
    // log.debug("wirte to DVR Video channel:" + src.remaining());
    if (this.writeBusy()) {
      this.close();
      // 写出错,设置网络超时错误。关闭连接。
      try {
        this.listener.timeout(this);
      } catch (IOException e) {
        log.error(e.toString(), e);
      }
    } else if (this.writeQueue.offer(src)) {
      // 如果当前Socket没有注册写操作.
      if (this.writeQueue.size() == 1
          && (this.selectionKey.interestOps() & SelectionKey.OP_WRITE) != SelectionKey.OP_WRITE) {
        this.selectionKey.interestOps(selectionKey.interestOps() | SelectionKey.OP_WRITE);
        this.selectionKey.selector().wakeup();
      }
    } else {
      log.warn("Write buffer queue full, client:" + this.toString());
    }

    while (sync && src.remaining() > 0) {
      synchronized (writeQueue) {
        try {
          writeQueue.wait();
        } catch (InterruptedException e) {
        }
      }
    }
  }
 /**
  * Blocks until all tasks have completed execution after a shutdown request, or the current thread
  * is interrupted, whichever happens first.
  *
  * @throws IOException if the sub-jobs died with an IOException.
  */
 public void terminate() throws IOException {
   try {
     try {
       synchronized (mJobs) {
         while (mBusy || !mJobs.isEmpty()) {
           mJobs.wait(NOT_DONE_SLEEP_TIME);
         }
       }
     } catch (final InterruptedException e) {
       // The Runnables may not get to see this before it finishes
       // (they may not even be looking), but it is better than
       // nothing.
       ProgramState.setAbort();
     } finally {
       shutdown(); // Ensure the queueing thread closes things down.
     }
     rethrow();
   } finally {
     ProgramState.clearAbort();
     try {
       synchronized (mQueueThread) {
         // waiting for queuethread to complete
         while (!mQueueDone) {
           mQueueThread.wait(NOT_DONE_SLEEP_TIME);
         }
       }
     } catch (final InterruptedException e) {
       // just exit
     }
   }
 }
Esempio n. 5
0
  @Override
  public void run() {
    do {
      while (_queue.isEmpty()) {
        try {
          synchronized (_queue) {
            _queue.wait();
          }
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }

      SpeculaTopLevelTransaction tx = _queue.poll();
      tx._tc.lock.lock();
      try {
        if (tx.validateCommit()) {
          tx.markForCommit();
        } else {
          tx.markForAbortion();
        }
      } finally {
        tx._tc.lock.unlock();
      }

      try {
        Thread.sleep(_delay);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    } while (true);
  }
Esempio n. 6
0
 public void run() {
   try {
     while (true) {
       Runnable cur;
       synchronized (q) {
         while ((cur = q.poll()) == null) q.wait();
       }
       cur.run();
       cur = null;
     }
   } catch (InterruptedException e) {
   }
 }
 /** Pr�ft, ob neue Packete angekommen sind */
 @Override
 public void run() {
   while (mc.isAlive()) {
     if (incomingMmrpPacketQueue.isEmpty()) {
       synchronized (incomingMmrpPacketQueue) {
         try {
           incomingMmrpPacketQueue.wait();
         } catch (InterruptedException e) {
           logger.log(Level.FINEST, "InterruptedException in Consumer-run()-method");
         }
       }
     } else {
       handleMmrpPacket();
     }
   }
 }
  @Override
  public void flush() throws IOException {
    try {
      // there is no reason to wait, if the worker is no longer running
      if (isRunning()) {
        synchronized (entries) {
          while (entries.size() > 0) {
            entries.wait();
          }
        }
      }

    } catch (InterruptedException ie) {
      throw new IOException(ie);
    }
  }
    @Override
    public void run() {
      final Queue<LoadRequest> queue = LoaderThreadHolder.REQUEST_QUEUE;
      for (; ; ) {
        try {
          LoadRequest request;
          synchronized (queue) {
            while ((request = queue.poll()) == null) {
              queue.wait();
            }
          }

          final ConcurrentClassLoader loader = request.requester;
          Class<?> result = null;
          synchronized (loader) {
            try {
              final SecurityManager sm = System.getSecurityManager();
              if (sm != null) {
                final LoadRequest localRequest = request;
                result =
                    AccessController.doPrivileged(
                        new PrivilegedExceptionAction<Class<?>>() {
                          public Class<?> run() throws ClassNotFoundException {
                            return loader.performLoadClassChecked(
                                localRequest.className,
                                localRequest.exportsOnly,
                                localRequest.resolve);
                          }
                        },
                        request.context);
              } else {
                result =
                    loader.performLoadClassChecked(
                        request.className, request.exportsOnly, request.resolve);
              }
            } finally {
              // no matter what, the requester MUST be notified
              request.result = result;
              request.done = true;
              loader.notifyAll();
            }
          }
        } catch (Throwable t) {
          // ignore
        }
      }
    }
Esempio n. 10
0
  private void performTask() throws InterruptedException {

    synchronized (queue) {
      while (queue.isEmpty()) {
        System.out.println(
            "Queue is empty. Consumer Thread("
                + Thread.currentThread().getName()
                + ")  is going to wait");
        queue.wait();
      }
      Task t = queue.remove();
      System.out.println(
          "Consumer Thread ("
              + Thread.currentThread().getName()
              + ")  has completed task: "
              + t.getTaskName());
      queue.notifyAll();
    }
  }
Esempio n. 11
0
    public void run() {
      while (true) {
        StringBuilder sb = new StringBuilder();

        // dequeue messages
        synchronized (messageQueue) {
          while (true) {
            String msg = messageQueue.poll();
            if (msg != null) {
              sb.append(msg);
              continue;
            } else {
              if (sb.length() > 0) break;
            }

            try {
              messageQueue.wait();
            } catch (InterruptedException e) {
              // interrupted and die
              return;
            }
          }
        }

        // write out messages
        String message = sb.toString();
        boolean wroteToStdout = false;

        // synchronized (outputStreamSet) {
        for (PrintStream out : outputStreamSet) {
          if (System.out.equals(out)) wroteToStdout = true;

          out.print(message);
        }
        // }

        if (!wroteToStdout) { // always write out the message to stdout
          System.out.print(message);
        }
      } // while (true)
    }
Esempio n. 12
0
  public void write(ByteBuffer src, boolean sync) throws IOException {
    if (log.isDebugEnabled() && src.remaining() < 4096 // 不写视频的日志,避免日志量太大了。
    ) {
      log.debug(String.format("write buffer size:%s, to:%s", src.remaining(), toString()));
    }

    if (this.writeBusy()) {
      this.writeBuffer();
      if (this.socket.socket().isClosed()) throw new IOException("socket is closed.");
      // 5秒内不重复输出警告消息。
      if (System.currentTimeMillis() - lastDropPackage > 5000) {
        log.warn(
            "Socket client is too slow, start to drop the write package. client:" + toString());
        lastDropPackage = System.currentTimeMillis();
        // 重新注册写操作。
        this.selectionKey.interestOps(selectionKey.interestOps() | SelectionKey.OP_WRITE);
        this.selectionKey.selector().wakeup();
      }
    } else {
      if (this.writeQueue.offer(src)) {
        // 如果当前Socket没有注册写操作.
        if (this.writeQueue.size() == 1
            && (this.selectionKey.interestOps() & SelectionKey.OP_WRITE) != SelectionKey.OP_WRITE) {
          this.selectionKey.interestOps(selectionKey.interestOps() | SelectionKey.OP_WRITE);
          this.selectionKey.selector().wakeup();
        }
        while (sync && src.remaining() > 0) {
          synchronized (writeQueue) {
            try {
              writeQueue.wait();
            } catch (InterruptedException e) {
            }
          }
        }
      } else {
        log.warn("Write buffer queue full, client:" + this.toString());
      }
    }
  }
  @Override
  public void run() {
    while (true) {
      try {
        synchronized (eventQueue) {
          // wait until we are notified that there are Events to consume
          eventQueue.wait();

          // wait for the command line to be free (not in use)
          synchronized (delegate) {
            System.out.println();
            System.out.println(); // make some room on the command line

            // display all Events in the queue
            System.out.println("New " + delegate.getDisplayName() + " alerts...");
            while (!eventQueue.isEmpty()) delegate.alert(eventQueue.poll());
          }
        }
      } catch (InterruptedException e) {
      }
    }
  }
Esempio n. 14
0
 public ByteBuffer getBuffer() {
   ByteBuffer buf = null;
   synchronized (queue) {
     if (queue.isEmpty()) {
       if (isWait()) { // 기다리는 모드이면
         try {
           queue.wait();
           /*
            * 인터럽트가 나는 상황은 어떤게 있을까?
            * 아마도 정상적인 루틴이 이루어지기 힘든 상황일 것이다. 따라서 null을 내보낸다.
            */
         } catch (InterruptedException e) {
           buf = null;
         }
       } else {
         buf = getBuffer(MEMORY_BLOCKSIZE);
       }
     } else {
       buf = queue.remove();
     }
   }
   return buf;
 }
 public void run() {
   try {
     long now, fthen, then;
     int frames = 0;
     fthen = System.currentTimeMillis();
     while (true) {
       then = System.currentTimeMillis();
       if (Config.profile) curf = prof.new Frame();
       synchronized (ui) {
         if (ui.sess != null) ui.sess.glob.oc.ctick();
         dispatch();
       }
       if (curf != null) curf.tick("dsp");
       uglyjoglhack();
       if (curf != null) curf.tick("aux");
       frames++;
       now = System.currentTimeMillis();
       if (now - then < fd) {
         synchronized (events) {
           events.wait(fd - (now - then));
         }
       }
       if (curf != null) curf.tick("wait");
       if (now - fthen > 1000) {
         fps = frames;
         frames = 0;
         dth = texhit;
         dtm = texmiss;
         texhit = texmiss = 0;
         fthen = now;
       }
       if (curf != null) curf.fin();
       if (Thread.interrupted()) throw (new InterruptedException());
     }
   } catch (InterruptedException e) {
   }
 }
Esempio n. 16
0
    @Override
    public void run() {
      /*
       This resolves a know deadlock that can occur if one thread is in the process of defining a package as part of
       defining a class, and another thread is defining the system package that can result in loading a class.  One holds
       the Package.pkgs lock and one holds the Classloader lock.
      */
      Package.getPackages();

      final Queue<LoadRequest> queue = LoaderThreadHolder.REQUEST_QUEUE;
      for (; ; ) {
        try {
          LoadRequest request;
          synchronized (queue) {
            while ((request = queue.poll()) == null) {
              queue.wait();
            }
          }

          final ModuleClassLoader loader = request.requester;
          Class<?> result = null;
          synchronized (loader) {
            try {
              result = loader.performLoadClass(request.className, request.exportsOnly);
            } finally {
              // no matter what, the requester MUST be notified
              request.result = result;
              request.done = true;
              loader.notifyAll();
            }
          }
        } catch (Throwable t) {
          // ignore
        }
      }
    }
Esempio n. 17
0
  public void run() {
    try {
      Thread drawthread = new HackThread(drawfun, "Render thread");
      drawthread.start();
      synchronized (drawfun) {
        while (state == null) drawfun.wait();
      }
      try {
        long now, then;
        long frames[] = new long[128];
        int framep = 0, waited[] = new int[128];
        while (true) {
          int fwaited = 0;
          Debug.cycle();
          UI ui = this.ui;
          then = System.currentTimeMillis();
          CPUProfile.Frame curf = null;
          if (Config.profile) curf = uprof.new Frame();
          synchronized (ui) {
            if (ui.sess != null) ui.sess.glob.ctick();
            dispatch();
            ui.tick();
            if ((ui.root.sz.x != w) || (ui.root.sz.y != h)) ui.root.resize(new Coord(w, h));
          }
          if (curf != null) curf.tick("dsp");

          BGL buf = new BGL();
          GLState.Applier state = this.state;
          rootdraw(state, ui, buf);
          if (curf != null) curf.tick("draw");
          synchronized (drawfun) {
            now = System.currentTimeMillis();
            while (bufdraw != null) drawfun.wait();
            bufdraw = new Frame(buf, state.cgl);
            drawfun.notifyAll();
            fwaited += System.currentTimeMillis() - now;
          }

          ui.audio.cycle();
          if (curf != null) curf.tick("aux");

          now = System.currentTimeMillis();
          long fd = bgmode ? this.bgfd : this.fd;
          if (now - then < fd) {
            synchronized (events) {
              events.wait(fd - (now - then));
            }
            fwaited += System.currentTimeMillis() - now;
          }

          frames[framep] = now;
          waited[framep] = fwaited;
          for (int i = 0, ckf = framep, twait = 0; i < frames.length; i++) {
            ckf = (ckf - 1 + frames.length) % frames.length;
            twait += waited[ckf];
            if (now - frames[ckf] > 1000) {
              fps = i;
              uidle = ((double) twait) / ((double) (now - frames[ckf]));
              break;
            }
          }
          framep = (framep + 1) % frames.length;

          if (curf != null) curf.tick("wait");
          if (curf != null) curf.fin();
          if (Thread.interrupted()) throw (new InterruptedException());
        }
      } finally {
        drawthread.interrupt();
        drawthread.join();
      }
    } catch (InterruptedException e) {
    } finally {
      ui.destroy();
    }
  }
Esempio n. 18
0
 public Session run(HavenPanel hp) throws InterruptedException {
   ui = hp.newui(null);
   ui.setreceiver(this);
   ui.bind(new LoginScreen(ui.root), 1);
   String username;
   boolean savepw = false;
   Utils.setpref("password", "");
   byte[] token = null;
   if (Utils.getpref("savedtoken", "").length() == 64)
     token = Utils.hex2byte(Utils.getpref("savedtoken", null));
   username = Utils.getpref("username", "");
   String authserver = (Config.authserv == null) ? address : Config.authserv;
   retry:
   do {
     byte[] cookie;
     if (initcookie != null) {
       username = inituser;
       cookie = initcookie;
       initcookie = null;
     } else if (token != null) {
       savepw = true;
       ui.uimsg(1, "token", username);
       while (true) {
         Message msg;
         synchronized (msgs) {
           while ((msg = msgs.poll()) == null) msgs.wait();
         }
         if (msg.id == 1) {
           if (msg.name == "login") {
             break;
           } else if (msg.name == "forget") {
             token = null;
             Utils.setpref("savedtoken", "");
             continue retry;
           }
         }
       }
       ui.uimsg(1, "prg", "Authenticating...");
       AuthClient auth = null;
       try {
         auth = new AuthClient(authserver, username);
         if (!auth.trytoken(token)) {
           auth.close();
           token = null;
           Utils.setpref("savedtoken", "");
           ui.uimsg(1, "error", "Invalid save");
           continue retry;
         }
         cookie = auth.cookie;
       } catch (java.io.IOException e) {
         ui.uimsg(1, "error", e.getMessage());
         continue retry;
       } finally {
         try {
           if (auth != null) auth.close();
         } catch (java.io.IOException e) {
         }
       }
     } else {
       String password;
       ui.uimsg(1, "passwd", username, savepw);
       while (true) {
         Message msg;
         synchronized (msgs) {
           while ((msg = msgs.poll()) == null) msgs.wait();
         }
         if (msg.id == 1) {
           if (msg.name == "login") {
             username = (String) msg.args[0];
             password = (String) msg.args[1];
             savepw = (Boolean) msg.args[2];
             break;
           }
         }
       }
       ui.uimsg(1, "prg", "Authenticating...");
       AuthClient auth = null;
       try {
         try {
           auth = new AuthClient(authserver, username);
         } catch (UnknownHostException e) {
           ui.uimsg(1, "error", "Could not locate server");
           continue retry;
         }
         if (!auth.trypasswd(password)) {
           auth.close();
           password = "";
           ui.uimsg(1, "error", "Username or password incorrect");
           continue retry;
         }
         cookie = auth.cookie;
         if (savepw) {
           if (auth.gettoken()) Utils.setpref("savedtoken", Utils.byte2hex(auth.token));
         }
       } catch (java.io.IOException e) {
         ui.uimsg(1, "error", e.getMessage());
         continue retry;
       } finally {
         try {
           if (auth != null) auth.close();
         } catch (java.io.IOException e) {
         }
       }
     }
     ui.uimsg(1, "prg", "Connecting...");
     try {
       sess = new Session(InetAddress.getByName(address), username, cookie);
     } catch (UnknownHostException e) {
       ui.uimsg(1, "error", "Could not locate server");
       continue retry;
     }
     Thread.sleep(100);
     while (true) {
       if (sess.state == "") {
         Utils.setpref("username", username);
         ui.destroy(1);
         break retry;
       } else if (sess.connfailed != 0) {
         String error;
         switch (sess.connfailed) {
           case 1:
             error = "Invalid authentication token";
             break;
           case 2:
             error = "Already logged in";
             break;
           case 3:
             error = "Could not connect to server";
             break;
           case 4:
             error = "This client is too old";
             break;
           case 5:
             error = "Authentication token expired";
             break;
           default:
             error = "Connection failed";
             break;
         }
         ui.uimsg(1, "error", error);
         sess = null;
         continue retry;
       }
       synchronized (sess) {
         sess.wait();
       }
     }
   } while (true);
   haven.error.ErrorHandler.setprop("usr", sess.username);
   return (sess);
   // (new RemoteUI(sess, ui)).start();
 }