public String GetKnnAsString(String featureVector) {
    // System.err.println(featureVector);
    // System.err.println(trainingVectors.size());
    FeatureVector fv = new FeatureVector(featureVector, 32);
    PriorityBlockingQueue<CategoryDistances> pbq = new PriorityBlockingQueue<>();
    ExecutorService pool = Executors.newFixedThreadPool(NumWorkers);
    String outp = "";

    for (FeatureVector elem : trainingVectors) {
      pool.execute(new EuclideanWorker(elem, fv, pbq));
    }
    pool.shutdown();
    while (!pool.isTerminated()) {;
    }

    for (int i = 0; i < K; i++) {
      CategoryDistances cd = pbq.poll();
      if (cd == null) {
        break;
      }
      outp += cd.toString() + VectorDelim;
    }
    // System.out.println(outp);
    return outp.substring(0, outp.length() - 1);
  }
Ejemplo n.º 2
0
  public static void addImage(BufferedImage img, UtmPose pose) {

    if (imagesDir != null) {
      try {
        File outputfile =
            new File(
                imagesDir.getAbsolutePath() + File.separator + "BoatImg" + (new Date()) + ".png");
        System.out.println("Writing to " + outputfile + " " + pose);
        ImageIO.write(img, "png", outputfile);
      } catch (IOException e) {
        System.out.println("Failed to write image to file: " + e);
      }
    } else {
      System.out.println("Do not know where to save images");
    }

    if (queue.size() > 100) {
      int v = rateS.getValue();
      int nv = Math.min(100, Math.max(v, (rateS.getValue() / 10)));
      if (v != nv) {
        rateS.setValue(nv);
      }
    }

    if (queue.size() < 1000) {
      queue.offer(new BufferedImageWithPose(img, pose));
      queueP.setValue(Math.min(100, queue.size()));
    } else {
      System.out.println("No longer queuing images, queue is full");
    }
  }
  private DataNodeIdentifier pickHeaviestLoad(DataNodeIdentifier otherNode) {
    DataNodeIdentifier replacementNode = null;

    PriorityBlockingQueue<DataNodeStatusPair> invertedStatusQueue =
        new PriorityBlockingQueue<DataNodeStatusPair>(
            datanodeStatuses.size(),
            new Comparator<DataNodeStatusPair>() {
              public int compare(DataNodeStatusPair a, DataNodeStatusPair b) {
                return -1 * a.compareTo(b);
              }
            });

    for (DataNodeStatusPair each : datanodeStatuses) {
      invertedStatusQueue.put(each);
    }

    while (replacementNode == null) {
      DataNodeStatusPair next = invertedStatusQueue.poll();
      DataNodeIdentifier nextId = next.getIdentifier();
      if (!nextId.equals(otherNode)) {
        replacementNode = nextId;
      }
    }

    return replacementNode;
  }
Ejemplo n.º 4
0
  static void b2487514Test() {
    PriorityBlockingQueue q = new PriorityBlockingQueue(10);
    int catchCount = 0;

    q.offer(new Integer(0));
    /*
     * Warm up the code cache to have toArray() compiled. The key here is
     * to pass a compatible type so that there are no exceptions when
     * executing the method body (ie the APUT_OBJECT bytecode).
     */
    for (int i = 0; i < 1000; i++) {
      Integer[] ints = (Integer[]) q.toArray(new Integer[5]);
    }

    /* Now pass an incompatible type which is guaranteed to throw */
    for (int i = 0; i < 1000; i++) {
      try {
        Object[] obj = q.toArray(new String[5]);
      } catch (ArrayStoreException success) {
        catchCount++;
      }
    }

    if (catchCount == 1000) {
      System.out.println("b2487514 passes");
    } else {
      System.out.println("b2487514 fails: catchCount is " + catchCount + " (expecting 1000)");
    }
  }
Ejemplo n.º 5
0
  @Override
  public Mission getMission(Sergeant s) {
    if (this.isEmpty()) return null;

    PriorityBlockingQueue<Mission> relevantQueue;
    Vector<Mission> temp = new Vector<Mission>();

    if (s.getPriority().equals(Sergeant.SHORTEST)) relevantQueue = this.minLength;
    else if (s.getPriority().equals(Sergeant.LONGEST)) relevantQueue = this.maxLength;
    else if (s.getPriority().equals(Sergeant.MINITEMS)) relevantQueue = this.minItems;
    else relevantQueue = this.maxItems;
    while (!relevantQueue.isEmpty()) {
      Mission candidate = relevantQueue.poll();
      temp.add(candidate);
      WarSim.LOG.fine("Testing Mission " + candidate.getName() + "(" + candidate.getSkill() + ")");
      if (s.getSkills().contains(candidate.getSkill())) {
        for (Mission tm : temp) relevantQueue.put(tm);
        return candidate;
      } else
        WarSim.LOG.fine(
            "The sergeant " + s.getName() + " can't execute mission " + candidate.getName());
    }
    for (Mission tm : temp) relevantQueue.put(tm);

    return null;
  }
Ejemplo n.º 6
0
 public static BufferedImage getImage() {
   try {
     BufferedImage b = queue.take().img;
     queueP.setValue(Math.min(100, queue.size()));
     return b;
   } catch (InterruptedException e) {
   }
   return null;
 }
Ejemplo n.º 7
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);
          }
        }
      }
    }
Ejemplo n.º 8
0
 public void compute() {
   /* Tant qu'il reste des points dans le tas */
   while (!q.isEmpty()) {
     /* Extraire le point le plus proche de l'arrivée */
     try {
       current = q.take();
       // update();
       /* appelle les obs */
       /* Trouver les voisins & MAJ -> dans une autre méthode */
       trouverVoisinEtMaj(current);
     } catch (InterruptedException e) {
       e.printStackTrace();
     }
   }
 }
Ejemplo n.º 9
0
 public void putEvent(GameEvent gameEvent) {
   try {
     queue.put(gameEvent);
   } catch (Exception e) {
     logger.error("<putEvent> but catch exception " + e.toString(), e);
   }
 }
 @Override
 public void run() {
   for (int i = 0; i < 1000; i++) {
     Event event = new Event(id, i);
     queue.add(event);
   }
 }
 public static void updateWorkQueue(ArrayList<String> newTaskUrl) {
   for (ImageLoadTask task : mHashMap.values()) {
     if (!newTaskUrl.contains(task.mImageUrl)) {
       mWorkQueue.remove(task);
       mHashMap.remove(task.mImageUrl);
     }
   }
 }
  /**
   * 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;
    }
  }
Ejemplo n.º 13
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());
     }
   }
 }
 public static void submitTask(String fileUrl, ImageLoadTask task) {
   Log.e(TAG, "execute a ImageLoadTask ! sWorkQueue.size() = " + mWorkQueue.size());
   if (mHashMap.get(fileUrl) == null) {
     mHashMap.put(fileUrl, task);
     mExecutor.execute(task);
   } else {
     Log.e(TAG, "there is already a task running !");
   }
 }
Ejemplo n.º 15
0
 @Override
 public synchronized String toString() {
   return Objects.toStringHelper(this)
       .add("runnerThreads", runnerThreads)
       .add("allSplits", allSplits.size())
       .add("pendingSplits", pendingSplits.size())
       .add("runningSplits", runningSplits.size())
       .add("blockedSplits", blockedSplits.size())
       .toString();
 }
Ejemplo n.º 16
0
 /** Removes the first task in the taskQueue with the taskKey */
 public boolean removeTaskByKey(String taskKey) {
   Iterator<MeasurementTask> it = taskQueue.iterator();
   while (it.hasNext()) {
     MeasurementTask task = it.next();
     if (task.getDescription().key.equals(taskKey)) {
       it.remove();
       return true;
     }
   }
   return false;
 }
  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;
  }
Ejemplo n.º 18
0
  private synchronized void splitFinished(PrioritizedSplitRunner split) {
    allSplits.remove(split);
    pendingSplits.remove(split);

    TaskHandle taskHandle = split.getTaskHandle();
    taskHandle.splitComplete(split);

    wallTime.add(System.nanoTime() - split.createdNanos);

    scheduleTaskIfNecessary(taskHandle);

    addNewEntrants();
  }
Ejemplo n.º 19
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);
  }
Ejemplo n.º 21
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());
      }
    }
  }
  public static void main(String[] args) {

    PriorityBlockingQueue<Event> queue = new PriorityBlockingQueue<Event>();

    Thread[] taskThreads = new Thread[5];

    // 初始这 5 个任务线程。
    for (int i = 0; i < taskThreads.length; i++) {
      Task task = new Task(i, queue);
      taskThreads[i] = new Thread(task);
    }

    // 启动这 5 个任务线程。
    for (Thread t : taskThreads) {
      t.start();
    }

    // 使用 join() 方法,让 main 线程等待 5 个任务线程结束。
    for (Thread t : taskThreads) {
      try {
        t.join();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }

    System.out.printf("Main: Queue Size: %d\n", queue.size());

    for (int i = 0; i < taskThreads.length * 1000; i++) {
      Event event = queue.poll();
      System.out.printf("Thread %s: Priority %d\n", event.getThread(), event.getPriority());
    }

    System.out.printf("Main: Queue Size: %d\n", queue.size());
    System.out.printf("Main: End of the program\n");
  }
Ejemplo n.º 23
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();
 }
 @Override
 public int hashCode() {
   final int prime = 31;
   int result = 1;
   result = prime * result + ((arrayBlockingQueue == null) ? 0 : arrayBlockingQueue.hashCode());
   result = prime * result + ((arrayDeque == null) ? 0 : arrayDeque.hashCode());
   result = prime * result + ((arrayList == null) ? 0 : arrayList.hashCode());
   result = prime * result + ((bar == null) ? 0 : bar.hashCode());
   result = prime * result + ((blockingDeque == null) ? 0 : blockingDeque.hashCode());
   result = prime * result + ((blockingQueue == null) ? 0 : blockingQueue.hashCode());
   result = prime * result + ((collection == null) ? 0 : collection.hashCode());
   result =
       prime * result + ((concurrentLinkedQueue == null) ? 0 : concurrentLinkedQueue.hashCode());
   result =
       prime * result + ((concurrentSkipListSet == null) ? 0 : concurrentSkipListSet.hashCode());
   result =
       prime * result + ((copyOnWriteArrayList == null) ? 0 : copyOnWriteArrayList.hashCode());
   result =
       prime * result + ((copyOnWriteArraySet == null) ? 0 : copyOnWriteArraySet.hashCode());
   result = prime * result + ((deque == null) ? 0 : deque.hashCode());
   result = prime * result + ((hashSet == null) ? 0 : hashSet.hashCode());
   result =
       prime * result + ((linkedBlockingDeque == null) ? 0 : linkedBlockingDeque.hashCode());
   result =
       prime * result + ((linkedBlockingQueue == null) ? 0 : linkedBlockingQueue.hashCode());
   result = prime * result + ((linkedHashSet == null) ? 0 : linkedHashSet.hashCode());
   result = prime * result + ((linkedList == null) ? 0 : linkedList.hashCode());
   result = prime * result + ((list == null) ? 0 : list.hashCode());
   result = prime * result + ((name == null) ? 0 : name.hashCode());
   result = prime * result + ((navigableSet == null) ? 0 : navigableSet.hashCode());
   result =
       prime * result + ((priorityBlockingQueue == null) ? 0 : priorityBlockingQueue.hashCode());
   result = prime * result + ((priorityQueue == null) ? 0 : priorityQueue.hashCode());
   result = prime * result + ((queue == null) ? 0 : queue.hashCode());
   result = prime * result + ((set == null) ? 0 : set.hashCode());
   result = prime * result + ((sortedSet == null) ? 0 : sortedSet.hashCode());
   result = prime * result + ((stack == null) ? 0 : stack.hashCode());
   result = prime * result + ((treeSet == null) ? 0 : treeSet.hashCode());
   result = prime * result + ((vector == null) ? 0 : vector.hashCode());
   return result;
 }
Ejemplo n.º 25
0
  /**
   * Submit a MeasurementTask to the scheduler. Caller of this method can broadcast an intent with
   * MEASUREMENT_ACTION to start the measurement immediately.
   */
  public boolean submitTask(MeasurementTask task) {
    try {
      // Immediately handles measurements created by user
      if (task.getDescription().priority == MeasurementTask.USER_PRIORITY) {
        return this.taskQueue.add(task);
      }

      if (taskQueue.size() >= Config.MAX_TASK_QUEUE_SIZE
          || pendingTasks.size() >= Config.MAX_TASK_QUEUE_SIZE) {
        return false;
      }
      // Automatically notifies the scheduler waiting on taskQueue.take()
      return this.taskQueue.add(task);
    } catch (NullPointerException e) {
      Logger.e("The task to be added is null");
      return false;
    } catch (ClassCastException e) {
      Logger.e("cannot compare this task against existing ones");
      return false;
    }
  }
Ejemplo n.º 26
0
  /** {@link java.lang.Thread#run()} */
  @Override
  public void run() {

    while (!(isExit())) {

      try {
        log.debug("trying to take from queue...");
        EventHandler h = handlersQueue.take();
        log.debug("took from the queue. executing " + h.getClass().getSimpleName());

        h.handle();

      } catch (InterruptedException ie) {
        log.fatal("EXCEPTION: Module Interrupted " + ie.getMessage());

      } catch (ClassCastException cce) {
        log.fatal("EXCEPTION: " + cce.getMessage());
        cce.printStackTrace();
      }
    }
  }
  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();
      }
    }
  }
Ejemplo n.º 28
0
  /**
   * Called from {@link Request#finish(String)}, indicating that processing of the given request has
   * finished.
   *
   * <p>Releases waiting requests for <code>request.getCacheKey()</code> if <code>
   * request.shouldCache()</code>.
   */
  void finish(Request request) {
    // Remove from the set of requests currently being processed.
    synchronized (mCurrentRequests) {
      mCurrentRequests.remove(request);
    }

    if (request.shouldCache()) {
      synchronized (mWaitingRequests) {
        String cacheKey = request.getCacheKey();
        Queue<Request> waitingRequests = mWaitingRequests.remove(cacheKey);
        if (waitingRequests != null) {
          if (VolleyLog.DEBUG) {
            VolleyLog.v(
                "Releasing %d waiting requests for cacheKey=%s.", waitingRequests.size(), cacheKey);
          }
          // Process all queued up requests. They won't be considered as in flight, but
          // that's not a problem as the cache has been primed by 'request'.
          mCacheQueue.addAll(waitingRequests);
        }
      }
    }
  }
Ejemplo n.º 29
0
  private void handleMeasurement() {
    if (!userConsented()) {
      Logger.i("Skipping measurement - User has not consented");
      return;
    }

    try {
      MeasurementTask task = taskQueue.peek();
      // Process the head of the queue.
      if (task != null && task.timeFromExecution() <= 0) {
        taskQueue.poll();
        Future<MeasurementResult> future;
        Logger.i("Processing task " + task.toString());
        // Run the head task using the executor
        if (task.getDescription().priority == MeasurementTask.USER_PRIORITY) {
          sendStringMsg("Scheduling user task:\n" + task);
          // User task can override the power policy. So a different task wrapper is used.
          future = measurementExecutor.submit(new UserMeasurementTask(task));
        } else {
          sendStringMsg("Scheduling task:\n" + task);
          future = measurementExecutor.submit(new PowerAwareTask(task, powerManager, this));
        }
        synchronized (pendingTasks) {
          pendingTasks.put(task, future);
        }

        MeasurementDesc desc = task.getDescription();
        long newStartTime = desc.startTime.getTime() + (long) desc.intervalSec * 1000;

        // Add a clone of the task if it's still valid.
        if (newStartTime < desc.endTime.getTime()
            && (desc.count == MeasurementTask.INFINITE_COUNT || desc.count > 1)) {
          MeasurementTask newTask = task.clone();
          if (desc.count != MeasurementTask.INFINITE_COUNT) {
            newTask.getDescription().count--;
          }
          newTask.getDescription().startTime.setTime(newStartTime);
          submitTask(newTask);
        }
      }
      // Schedule the next measurement in the taskQueue
      task = taskQueue.peek();
      if (task != null) {
        long timeFromExecution =
            Math.max(task.timeFromExecution(), Config.MIN_TIME_BETWEEN_MEASUREMENT_ALARM_MSEC);
        measurementIntentSender =
            PendingIntent.getBroadcast(
                this,
                0,
                new UpdateIntent("", UpdateIntent.MEASUREMENT_ACTION),
                PendingIntent.FLAG_CANCEL_CURRENT);
        alarmManager.set(
            AlarmManager.RTC_WAKEUP,
            System.currentTimeMillis() + timeFromExecution,
            measurementIntentSender);
      }
    } catch (IllegalArgumentException e) {
      // Task creation in clone can create this exception
      Logger.e("Exception when cloning task");
      sendStringMsg("Exception when cloning task: " + e);
    } catch (Exception e) {
      // We don't want any unexpected exception to crash the process
      Logger.e("Exception when handling measurements", e);
      sendStringMsg("Exception running task: " + e);
    }
    persistState();
  }
Ejemplo n.º 30
0
 public void makeRequest(final CacheRequest request) {
   requests.put(request);
 }