Пример #1
0
 @Override
 public void put(T payload) {
   synchronized (collectedTuples) {
     collectedTuples.add(payload);
     collectedTuples.notifyAll();
   }
 }
Пример #2
0
 /** 提交新的客户端写请求于主服务线程的回应池中 */
 public static void processWriteRequest(SelectionKey key) {
   synchronized (wpool) {
     wpool.add(wpool.size(), key);
     wpool.notifyAll();
   }
   selector.wakeup(); // 解除selector的阻塞状态,以便注册新的通道
 }
 public static void processRequest(Socket requestToHandle) {
   synchronized (pool) {
     pool.add(pool.size(), requestToHandle);
     log.debug("#####" + pool.size() + "#####");
     pool.notifyAll();
   }
 }
Пример #4
0
    @Override
    public void run() {
      while (true) {
        synchronized (shareData) {
          while (shareData.isEmpty()) {
            try {
              System.out.println(Thread.currentThread().getName() + " 数据为空,等待生产...");
              shareData.wait();
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
          }

          Integer obj = shareData.get(0);
          shareData.remove(obj);
          System.out.println(
              Thread.currentThread().getName() + " 消费数据:" + obj + ", 剩余:" + shareData.size());

          try {
            Thread.sleep(1000);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }

          shareData.notifyAll();
        }
      }
    }
Пример #5
0
    public void run() {
      try {
        long startTime = System.currentTimeMillis();
        for (int i = start; i < end; i++) {
          TableSchema tableSchema = new TableSchema("T_MANY_TABLE_" + i);
          tableSchema.addColumn("Col1");
          tableSchema.addColumn("Col2");
          tableSchema.addColumn("Col3");
          tableSchema.addColumn("Col4");
          tableSchema.addColumn("Col5");
          tableSchema.addColumn("Col6");

          CTable.createTable(conf, tableSchema);
        }
        long endTime = System.currentTimeMillis();
        System.out.println((end - start) + " created, " + (endTime - startTime) + " ms elapsed");

      } catch (Exception e) {
        error = e;
        return;
      } finally {
        synchronized (threads) {
          threads.notifyAll();
        }
      }
    }
Пример #6
0
  public void msgGlobalFailure() throws IOException {
    synchronized (channels) {
      globalFailedCounter++;
      channels.notifyAll();
    }

    log.debug("Got SSH_MSG_REQUEST_FAILURE");
  }
 /*     */ public static void timestamp(String label) {
   /* 203 */ long tm = System.nanoTime();
   /* 204 */ if ((PERF_LOG_ENABLED) && (logger != null) && (logger.isActive()))
     /* 205 */ synchronized (queue) {
       /* 206 */ queue.add(new Record(tm, label));
       /* 207 */ queue.notifyAll();
       /*     */ }
   /*     */ }
Пример #8
0
  public void msgGlobalSuccess() throws IOException {
    synchronized (channels) {
      globalSuccessCounter++;
      channels.notifyAll();
    }

    log.debug("Got SSH_MSG_REQUEST_SUCCESS");
  }
  /**
   * Process events in the queue as they are added. The queue must be synchronized for thread safety
   * but we must be careful not to block for too long or else new events get blocked from being
   * added to the queue causing long delays. The design is to process events in batches. This allows
   * for the most efficient use of computer cycles since much of the time the queue will not be
   * blocked.
   *
   * <p>This method was modified by tap on 6/17/2004 to allow both efficient event processing and
   * thread safety. Later optimized by msekoranja.
   */
  public void run() {
    // eventBatch is local and only referenced by a single thread so we
    // don't have to synchronize it
    int eventsToProcess = 0;
    Event[] eventBatch = new Event[0];

    while (!_killed) {
      try {
        // for performance reasons we don't want to block for too long
        // synchronize _queue for thread safety
        // copy all of the new queued events to the local batch and clear _queue
        synchronized (_queue) {
          // wait for new requests
          while (!_killed && _queue.isEmpty()) _queue.wait();

          if (!_killed) {
            eventsToProcess = _queue.size();
            // create new instance of batch array only if necessary
            if (eventsToProcess > eventBatch.length) eventBatch = new Event[eventsToProcess];

            // only copy (will not recreate array)
            _queue.toArray(eventBatch);
            _queue.clear();

            // notify queue clean-up
            _queue.notifyAll();
          }
        }

        // process all events in the local batch until it is empty
        for (int i = 0; !_killed && i < eventsToProcess; i++) {
          // catch all exceptions, so that one buggy listener does not harm the others
          final Event event = eventBatch[i];
          try {
            // remove from override id
            final Object overrideId = eventBatch[i]._overrideId;
            if (overrideId != null) {
              synchronized (_overrideMap) {
                _overrideMap.remove(overrideId);
              }
            }

            event.dispatch();
          } catch (Throwable th) {
            th.printStackTrace();
          }

          decrementSyncCounter(eventBatch[i]);

          eventBatch[i] = null; // allow to be gc'ed
          Thread.yield();
        }

      } catch (Throwable th) {
        th.printStackTrace();
      }
    }
  }
 @Override
 public void serviceChanged(ServiceEvent event) {
   synchronized (serviceEvents) {
     log.debug(
         "ServiceChanged type=" + ConstantsHelper.serviceEvent(event.getType()) + " for " + event);
     serviceEvents.add(event);
     serviceEvents.notifyAll();
   }
 }
 @Override
 public void bundleChanged(BundleEvent event) {
   synchronized (bundleEvents) {
     log.debug(
         "BundleChanged type=" + ConstantsHelper.bundleEvent(event.getType()) + " for " + event);
     bundleEvents.add(event);
     bundleEvents.notifyAll();
   }
 }
Пример #12
0
 public void addTask(Upload task) {
   synchronized (taskQueue) {
     if (null != task) {
       taskQueue.add(task);
       taskQueue.notifyAll();
       System.out.println("task id " + task.getInfo() + " submit!");
     }
   }
 }
Пример #13
0
 public void BatchAddTask(Upload[] tasks) {
   synchronized (taskQueue) {
     for (Upload task : tasks) {
       if (task != null) {
         taskQueue.add(task);
         taskQueue.notifyAll();
         System.out.println("task id " + task.getInfo() + " submit!");
       }
     }
   }
 }
Пример #14
0
 /** Removes the SimpleTimer. */
 public void removeSimpleTimer() {
   synchronized (_events) {
     runn.setAnswer(false);
     _events.clear();
     _eventTimes.clear();
     _events.notifyAll();
   }
   synchronized (_readyEvents) {
     _readyEvents.clear();
     _readyEvents.notifyAll();
   }
 }
Пример #15
0
 private static void closeAndClear(List<PrintWriter> writers) {
   for (PrintWriter out : writers) {
     out.close();
   }
   // By clearning the writers and notify the thread waiting on it,
   // we will prevent JobHistory.moveToDone() from
   // waiting on writer
   synchronized (writers) {
     writers.clear();
     writers.notifyAll();
   }
 }
 @Override
 public void frameworkEvent(FrameworkEvent event) {
   synchronized (frameworkEvents) {
     log.debug(
         "FrameworkEvent type="
             + ConstantsHelper.frameworkEvent(event.getType())
             + " for "
             + event);
     frameworkEvents.add(event);
     frameworkEvents.notifyAll();
   }
 }
  /**
   * Stops the FelixStartLevel thread on system shutdown. Shutting down the thread explicitly is
   * required in the embedded case, where Felix may be stopped without the Java VM being stopped. In
   * this case the FelixStartLevel thread must be stopped explicitly.
   *
   * <p>This method is called by the {@link StartLevelActivator#stop(BundleContext)} method.
   */
  void stop() {
    synchronized (m_requests) {
      if (m_thread != null) {
        // Null thread variable to signal to the thread that
        // we want it to exit.
        m_thread = null;

        // Wake up the thread, if it is currently in the wait() state
        // for more work.
        m_requests.notifyAll();
      }
    }
  }
Пример #18
0
  // method to add an element in the list
  public void addElement(String element) {
    System.out.println("Opening...");
    synchronized (synchedList) {

      // add an element and notify all that an element exists
      synchedList.add(element);
      System.out.println("New Element:'" + element + "'");

      synchedList.notifyAll();
      System.out.println("notifyAll called!");
    }
    System.out.println("Closing...");
  }
Пример #19
0
  /** Ends the request and unlock the write lock */
  public void endRequest(final OChannelBinaryClient iNetwork) throws IOException {
    if (iNetwork == null) return;

    try {
      iNetwork.flush();
      // } catch (IOException e) {
      // IGNORE IT BECAUSE IT COULD BE CALLED AFTER A NETWORK ERROR TO RELEASE THE SOCKET
    } finally {

      iNetwork.getLockWrite().unlock();

      if (debug) System.out.println("<- req: " + getSessionId());

      synchronized (networkPool) {
        networkPool.notifyAll();
      }
    }
  }
Пример #20
0
 private void consume() throws InterruptedException {
   synchronized (taskQueue) {
     while (taskQueue.isEmpty()) {
       System.out.println(
           "Queue is empty "
               + Thread.currentThread().getName()
               + " is waiting , size: "
               + taskQueue.size()
               + "Time: "
               + new Date(System.currentTimeMillis()));
       taskQueue.wait();
     }
     Thread.sleep(1000);
     int i = (Integer) taskQueue.remove(0);
     System.out.println("Consumed: " + i);
     taskQueue.notifyAll();
   }
 }
  private void run_suspension(SuspensionServiceThread[] threads, List<Socket> connSockPool) {
    while (true) {
      try {
        // accept connection from connection queue
        Socket connSock = welcomeSocket.accept();
        if (Debug.IS_DEBUG) {
          System.out.println("Main thread retrieve connection from " + connSock);
        }

        synchronized (connSockPool) {
          connSockPool.add(connSock);
          connSockPool.notifyAll();
        }

      } catch (Exception e) {
        System.out.println("Suspension Server run failed.");
      }
    }
  }
  public void setStartLevel(int startlevel, FrameworkListener... listeners) {
    Object sm = System.getSecurityManager();

    if (sm != null) {
      ((SecurityManager) sm)
          .checkPermission(new AdminPermission(m_felix, AdminPermission.STARTLEVEL));
    }

    if (startlevel <= 0) {
      throw new IllegalArgumentException("Start level must be greater than zero.");
    }

    synchronized (m_requests) {
      if (m_thread == null) {
        throw new IllegalStateException("No inital startlevel yet");
      }
      // Queue request.
      m_requestListeners.add(listeners);
      m_requests.add(new Integer(startlevel));
      m_requests.notifyAll();
    }
  }
Пример #23
0
    @Override
    public void run() {
      while (true) {
        synchronized (shareData) {
          while (shareData.size() == SIZE) {
            try {
              System.out.println(Thread.currentThread().getName() + " 数据是满的,等待消费...");
              shareData.wait();
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
          }

          Integer obj = random.nextInt(100);
          shareData.add(obj);
          System.out.println(
              Thread.currentThread().getName() + " 生产数据:" + obj + ", 总共:" + shareData.size());

          shareData.notifyAll();
        }
      }
    }
  public void dispose() {
    _killed = true;
    _dispatcherThread = null;

    // notify _queue
    synchronized (_queue) {
      _queue.notifyAll();
    }

    // destroy all locks
    synchronized (_sourcesEventCount) {
      Iterator iter = _sourcesEventCount.values().iterator();
      while (iter.hasNext()) ((SynchronizedLimitedInt) iter.next()).destroy();

      _sourcesEventCount.clear();
    }

    // clear _overrideMap
    synchronized (_overrideMap) {
      _overrideMap.clear();
    }
  }
  /**
   * This method is currently only called by the by the thread that calls the Felix.start() method
   * and the shutdown thread when the framework is shutting down.
   *
   * @param startlevel
   */
  /* package */ void setStartLevelAndWait(int startlevel) {
    Object request = new Integer(startlevel);
    synchronized (request) {
      synchronized (m_requests) {
        // Start thread if necessary.
        startThread();
        // Queue request.
        m_requestListeners.add(null);
        m_requests.add(request);
        m_requests.notifyAll();
      }

      try {
        request.wait();
      } catch (InterruptedException ex) {
        // Log it and ignore since it won't cause much of an issue.
        m_felix
            .getLogger()
            .log(
                Logger.LOG_WARNING, "Wait for start level change during shutdown interrupted.", ex);
      }
    }
  }
  protected void queueEvent(Event ev, boolean doNotBlockRequired) {
    if (_killed) return;

    // increment counter, will block if limit will be reached
    // avoid deadlock allowing recursive queue-ing
    boolean doNotBlock = doNotBlockRequired || (Thread.currentThread() == _dispatcherThread);
    incrementSyncCounter(ev, doNotBlock);

    synchronized (_queue) {
      while (!doNotBlock && _queue.size() >= _queueLimit && !_killed) {
        try {
          _queue.wait();
        } catch (InterruptedException e) {
        }
      }

      if (_killed) return;

      _queue.add(ev);
      // notify event arrival
      _queue.notifyAll();
    }
  }
Пример #27
0
 /** 处理客户请求,管理用户的联结池,并唤醒队列中的线程进行处理 */
 public static void processRequest(SelectionKey key) {
   synchronized (wrpool) {
     wrpool.add(wrpool.size(), key);
     wrpool.notifyAll();
   }
 }
Пример #28
0
  public void handleMessage(byte[] msg, int msglen) throws IOException {
    if (msg == null) {

      log.debug("HandleMessage: got shutdown");

      synchronized (listenerThreads) {
        for (IChannelWorkerThread lat : listenerThreads) {
          lat.stopWorking();
        }
        listenerThreadsAllowed = false;
      }

      synchronized (channels) {
        shutdown = true;

        for (Channel c : channels) {
          synchronized (c) {
            c.EOF = true;
            c.state = Channel.STATE_CLOSED;
            c.setReasonClosed("The connection is being shutdown");
            c.closeMessageRecv = true; /*
													* You never know, perhaps
													* we are waiting for a
													* pending close message
													* from the server...
													*/
            c.notifyAll();
          }
        }

        channels.clear();
        channels.notifyAll(); /* Notify global response waiters */
        return;
      }
    }

    switch (msg[0]) {
      case Packets.SSH_MSG_CHANNEL_OPEN_CONFIRMATION:
        msgChannelOpenConfirmation(msg, msglen);
        break;
      case Packets.SSH_MSG_CHANNEL_WINDOW_ADJUST:
        msgChannelWindowAdjust(msg, msglen);
        break;
      case Packets.SSH_MSG_CHANNEL_DATA:
        msgChannelData(msg, msglen);
        break;
      case Packets.SSH_MSG_CHANNEL_EXTENDED_DATA:
        msgChannelExtendedData(msg, msglen);
        break;
      case Packets.SSH_MSG_CHANNEL_REQUEST:
        msgChannelRequest(msg, msglen);
        break;
      case Packets.SSH_MSG_CHANNEL_EOF:
        msgChannelEOF(msg, msglen);
        break;
      case Packets.SSH_MSG_CHANNEL_OPEN:
        msgChannelOpen(msg, msglen);
        break;
      case Packets.SSH_MSG_CHANNEL_CLOSE:
        msgChannelClose(msg, msglen);
        break;
      case Packets.SSH_MSG_CHANNEL_SUCCESS:
        msgChannelSuccess(msg, msglen);
        break;
      case Packets.SSH_MSG_CHANNEL_FAILURE:
        msgChannelFailure(msg, msglen);
        break;
      case Packets.SSH_MSG_CHANNEL_OPEN_FAILURE:
        msgChannelOpenFailure(msg, msglen);
        break;
      case Packets.SSH_MSG_GLOBAL_REQUEST:
        msgGlobalRequest(msg, msglen);
        break;
      case Packets.SSH_MSG_REQUEST_SUCCESS:
        msgGlobalSuccess();
        break;
      case Packets.SSH_MSG_REQUEST_FAILURE:
        msgGlobalFailure();
        break;
      default:
        throw new IOException("Cannot handle unknown channel message " + (msg[0] & 0xff));
    }
  }
Пример #29
0
  public void run() {
    String LOG_TAG = ArduinoSubChannel.TAG + "worker";

    while (workerRun) {

      if (a3pSession != null) {
        USBPayload nextPayload = a3pSession.getNextPayload();

        if (nextPayload == null) {
          try {
            synchronized (this) {
              this.wait(100);
            }
          } catch (InterruptedException e) {
            // Do nothing for now.
          }
        } else {

          // Process the payload here!
          if (DEBUG_VERBOSE) {
            Log.d(LOG_TAG, "Received payload for sensorID:  " + nextPayload.getSensorID());
          }

          // If this is a sensor enumeration packet, update our configuration information
          // Note:  this currently allows USBManager to be reconfigured while running
          //        which seems to make sense, since we're hoping to try to reconnect to
          //        the Arduino while live (although we may need a new A3PSession)
          //
          // We may later replace this processing with a virtual 'sensor 0'
          //
          if (nextPayload.getSensorID() == 0) {
            Log.d(LOG_TAG, "We got a system control packet!");
            String payloadString = nextPayload.payloadAsString();
            if (payloadString.length() >= 1 && payloadString.charAt(0) == '!') {
              Log.d(LOG_TAG, "Processing identification string: " + payloadString);

              // Split the ID string on the ; character, ignoring the first character
              String[] ids = payloadString.substring(1).split(";");

              for (int i = 0; i < ids.length; i++) {
                int temp = ids[i].indexOf(",");
                ids[i] = ids[i].substring(0, temp);
                try {
                  ids[i] = "" + Long.parseLong(ids[i]); // Trim off leading zeros or whitespace
                } catch (NumberFormatException e) {
                  Log.e(LOG_TAG, "Error parsing sensor id: " + ids[i]);
                }
                Log.d(LOG_TAG, "Found sensor id: " + ids[i]);
              }

              synchronized (deviceIDs) {
                deviceIDs.clear();
                deviceIDs.addAll(Arrays.asList(ids));
                Log.d(LOG_TAG, "notifying with devices " + deviceIDs.size());
                deviceIDs.notifyAll();
              }
            }
          } else {

            SensorDataPacket sdp;
            if (nextPayload.isReadingSeries()) {
              sdp =
                  new SensorDataPacket(
                      nextPayload.getRawBytes(),
                      nextPayload.getSeriesTimestamp(),
                      nextPayload.getNumOfReadingsInSeries());
            } else {
              sdp =
                  new SensorDataPacket(
                      nextPayload.getRawBytes(), nextPayload.getAndroidTimeStamp());
            }
            mSensorManager.addSensorDataPacket(String.valueOf(nextPayload.getSensorID()), sdp);
          }
        }
      }
    }
  }