@Override
 public void run() {
   for (int i = 0; i < 1000; i++) {
     Event event = new Event(id, i);
     queue.add(event);
   }
 }
Beispiel #2
0
 synchronized void completeInitWork(InitWork iw) {
   m_jobs.remove(iw.getClass());
   for (Class<? extends InitWork> cls : iw.m_blockees) {
     InitWork blockee = m_jobs.get(cls);
     boolean success = blockee.m_blockers.remove(iw.getClass());
     assert (success);
     if (blockee.m_blockers.size() == 0) {
       m_readyJobs.add(blockee);
     }
   }
   if (m_jobs.size() == 0) {
     // tell all the threads to stop
     for (int i = 0; i < m_threadCount; ++i) {
       m_readyJobs.add(new COMPLETION_WORK());
     }
   }
 }
  /**
   * Adds a Request to the dispatch queue.
   *
   * @param request The request to service
   * @return The passed-in request
   */
  public Request add(Request request) {
    // Tag the request as belonging to this queue and add it to the set of current requests.
    request.setRequestQueue(this);

    // Rewrite the url, in case of GET requests
    if (mUrlRewriter != null) {
      request.setUrl(mUrlRewriter.rewriteUrl(request));
    }

    synchronized (mCurrentRequests) {
      mCurrentRequests.add(request);
    }

    // Process requests in the order they are added.
    request.setSequence(getSequenceNumber());
    request.addMarker("add-to-queue");

    // If the request is uncacheable, skip the cache queue and go straight to the network.
    if (!request.shouldCache()) {
      mNetworkQueue.add(request);
      return request;
    }

    // Insert request into stage if there's already a request with the same cache key in flight.
    synchronized (mWaitingRequests) {
      String cacheKey = request.getCacheKey();
      if (mWaitingRequests.containsKey(cacheKey)) {
        // There is already a request in flight. Queue up.
        Queue<Request> stagedRequests = mWaitingRequests.get(cacheKey);
        if (stagedRequests == null) {
          stagedRequests = new LinkedList<Request>();
        }
        stagedRequests.add(request);
        mWaitingRequests.put(cacheKey, stagedRequests);
        if (VolleyLog.sDebug) {
          VolleyLog.v("Request for cacheKey=%s is in flight, putting on hold.", cacheKey);
        }
      } else {
        // Insert 'null' queue for this cacheKey, indicating there is now a request in
        // flight.
        mWaitingRequests.put(cacheKey, null);
        mCacheQueue.add(request);
      }
      return request;
    }
  }
Beispiel #4
0
    public void run() {
      while (stillAlive.get()) {
        synchronized (this) {
          try {
            ScheduledJob job = schedule.peek();

            if (job == null) {
              // If null, wake up every minute or so to see if there's something to do.
              // Most likely there will not be.
              try {
                this.wait(TIMEOUT_MS);
              } catch (InterruptedException e) {
                // interruption should occur when items are added or removed from the queue.
              }
            } else {
              // We've passed the job execution time, so we will run.
              if (!job.getScheduledExecution().isAfterNow()) {
                // Run job. The invocation of jobs should be quick.
                ScheduledJob runningJob = schedule.poll();
                logger.info("Scheduler attempting to run " + runningJob.getId());

                // Execute the job here
                try {
                  executionManager.execute(runningJob.getId(), runningJob.isDependencyIgnored());
                } catch (JobExecutionException e) {
                  logger.info("Could not run job. " + e.getMessage());
                }
                // Immediately reschedule if it's possible. Let the execution manager
                // handle any duplicate runs.
                if (runningJob.updateTime()) {
                  schedule.add(runningJob);
                  saveSchedule();
                } else {
                  // No need to keep it in the schedule.
                  removeScheduledJob(runningJob);
                }
              } else {
                // wait until job run
                long millisWait =
                    Math.max(
                        0, job.getScheduledExecution().getMillis() - (new DateTime()).getMillis());
                try {
                  this.wait(Math.min(millisWait, TIMEOUT_MS));
                } catch (InterruptedException e) {
                  // interruption should occur when items are added or removed from the queue.
                }
              }
            }
          } catch (Exception e) {
            logger.error("Unexpected exception has been thrown in scheduler", e);
          } catch (Throwable e) {
            logger.error("Unexpected throwable has been thrown in scheduler", e);
          }
        }
      }
    }
Beispiel #5
0
  Inits(RealVoltDB rvdb, int threadCount) {
    m_rvdb = rvdb;
    m_config = rvdb.m_config;
    // determine if this is a rejoining node
    // (used for license check and later the actual rejoin)
    if (m_config.m_startAction.doesRejoin()) {
      m_isRejoin = true;
    } else {
      m_isRejoin = false;
    }
    m_threadCount = threadCount;
    m_deployment = rvdb.m_catalogContext.getDeployment();

    // find all the InitWork subclasses using reflection and load them up
    Class<?>[] declaredClasses = Inits.class.getDeclaredClasses();
    for (Class<?> cls : declaredClasses) {
      // skip base classes and fake classes
      if (cls == InitWork.class) continue;
      if (cls == COMPLETION_WORK.class) continue;

      if (InitWork.class.isAssignableFrom(cls)) {
        InitWork instance = null;
        try {
          Constructor<?> constructor = cls.getDeclaredConstructor(Inits.class);
          instance = (InitWork) constructor.newInstance(this);
        } catch (Exception e) {
          VoltDB.crashLocalVoltDB("Critical error loading class " + cls.getName(), true, e);
        }
        m_jobs.put(instance.getClass(), instance);
      }
    }

    // make blockers and blockees symmetrical
    for (InitWork iw : m_jobs.values()) {
      for (Class<? extends InitWork> cls : iw.m_blockers) {
        InitWork blocker = m_jobs.get(cls);
        blocker.m_blockees.add(iw.getClass());
      }
    }

    // collect initially ready jobs
    List<Class<? extends InitWork>> toRemove = new ArrayList<Class<? extends InitWork>>();
    for (Entry<Class<? extends InitWork>, InitWork> e : m_jobs.entrySet()) {
      if (e.getValue().m_blockers.size() == 0) {
        toRemove.add(e.getKey());
        m_readyJobs.add(e.getValue());
      }
    }
  }
Beispiel #6
0
 public Dijkstra(Circuit circuit) {
   super();
   this.circuit = circuit;
   dist = new double[circuit.getHeight()][circuit.getWidth()];
   /* Initialisation du tableau de distance */
   for (int i = 0; i < dist.length; i++) {
     for (int j = 0; j < dist[0].length; j++) {
       dist[i][j] = Double.POSITIVE_INFINITY;
     }
   }
   q = new PriorityBlockingQueue<Vecteur>(100, new ComparatorDijk(dist));
   l = new ArrayList<UpdateEventListener>();
   /* Initialisation du tas */
   for (Vecteur v : circuit.getListeArrivees()) {
     q.add(v);
     dist[(int) v.getX()][(int) v.getY()] = 0;
   }
   compute();
 }
  private DataNodeIdentifier pickReplacement(
      SegmentGroup affectedGroup, DataNodeIdentifier oldNode) {
    DataNodeIdentifier replacementNode = null;
    List<DataNodeStatusPair> removedPairs = new ArrayList<DataNodeStatusPair>();

    while (replacementNode == null) {
      DataNodeStatusPair next = datanodeStatuses.poll();
      removedPairs.add(next);
      DataNodeIdentifier nextId = next.getIdentifier();
      if (!nextId.equals(oldNode) && !affectedGroup.isMember(nextId)) {
        replacementNode = nextId;
      }
    }

    for (DataNodeStatusPair each : removedPairs) {
      datanodeStatuses.add(each);
    }

    return replacementNode;
  }
  public void run() {
    MPacket received = null;
    MPacket current = null;
    int prevSeqNum = 0;
    Client client = null;
    if (Debug.debug) System.out.println("Starting ClientListenerThread");
    while (true) {
      try {
        received = (MPacket) mSocket.readObject();

        if (received.event == MPacket.HELLO) {
          MPacket helloResp = new MPacket(localClient.getName(), MPacket.HELLO, MPacket.HELLO_RESP);
          mSocket.writeObject(helloResp);
        }

        if (amServer.get()) {
          if (received.type == MPacket.ACTION_REQUEST) {
            if (Debug.debug) System.out.println("Received Request Packet: " + received);
            eventQueue.add(received);
          } else if (received.type == MPacket.REBROADCAST) {
            if (Debug.debug) System.out.println("Received Rebroadcast Packet: " + received);
            eventQueue.add(received);
          }
        } else {
          if (received.type == MPacket.ACTION || received.type == MPacket.SYNC) {
            if (Debug.debug) System.out.println("Received Sequence Packet: " + received);
            listenerQueue.add(received);
            System.out.println("LISTENER QUEUE: " + listenerQueue);
          } else if (received.type == MPacket.REBROADCAST) {
            if (Debug.debug) System.out.println("Received Rebroadcast Packet: " + received);
            eventQueue.add(received);
          }
        }
      } catch (IOException e) {
        e.printStackTrace();
      } catch (ClassNotFoundException e) {
        e.printStackTrace();
      }
    }
  }
Beispiel #9
0
  public void trouverVoisinEtMaj(Vecteur point) {
    /* Autour du point (i,j) */
    int x = (int) point.getX();
    int y = (int) point.getY();
    /* Boucle: pour di allant de -1 à 1 et dj allant de -1 à 1 */
    for (int di = -1; di <= 1; di++) {
      for (int dj = -1; dj <= 1; dj++) {
        Vecteur d = new Vecteur(x + di, y + dj);
        /* Eliminer les indices inintéressants (continue) */
        if (di == 0 && dj == 0) {
          continue;
        }
        /* Eliminer les mauvais voisins */
        if (!ToolsTerrain.isRunnable(circuit.getTerrain(d))) {
          continue;
        }

        if ((di + x >= circuit.getHeight())
            || (dj + y >= circuit.getWidth())
            || (di + x < 0)
            || (dj + y < 0)) {
          continue;
        }
        if (dist[x][y] == 0) {
          if (VTools.prodScal(circuit.getDirectionArrivee(), new Vecteur(di, dj)) > 0) {
            continue;
          }
        }
        /* Compare la nouvelle distance avec la distance actuelle */
        int poids = poids(di, dj);
        if (dist[x + di][y + dj] > dist[x][y] + poids) {
          q.remove(d);
          dist[x + di][y + dj] = dist[x][y] + poids;
          q.add(d);
        }
      }
    }
  }
  private void updateStatus(DataNodeIdentifier oldNode, DataNodeIdentifier replacementNode) {
    int segmentsPerSegmentGroup = coordinator.getSegmentsPerSegmentGroup();

    DataNodeStatusPair oldPair = null;
    DataNodeStatusPair newPair = null;

    for (DataNodeStatusPair eachPair : datanodeStatuses) {
      if (oldNode.equals(eachPair.getIdentifier())) {
        oldPair = eachPair;
      } else if (replacementNode.equals(eachPair.getIdentifier())) {
        newPair = eachPair;
      }
    }

    oldPair.getStatus().addStoredSegments(-1 * segmentsPerSegmentGroup);
    newPair.getStatus().addStoredSegments(segmentsPerSegmentGroup);

    datanodeStatuses.remove(oldPair);
    datanodeStatuses.remove(newPair);

    datanodeStatuses.add(oldPair);
    datanodeStatuses.add(newPair);
  }
Beispiel #11
0
 /**
  * Adds the job to the schedule and then interrupts so it will update its wait time.
  *
  * @param job
  */
 public synchronized void addScheduledJob(ScheduledJob job) {
   logger.info("Adding " + job + " to schedule.");
   schedule.add(job);
   this.interrupt();
 }