Exemplo n.º 1
1
  private static void showThreads(PrintStream pw, ThreadGroup g, Thread current) {
    int nthreads = g.activeCount();
    pw.println("\nThread Group = " + g.getName() + " activeCount= " + nthreads);
    Thread[] tarray = new Thread[nthreads];
    int n = g.enumerate(tarray, false);

    for (int i = 0; i < n; i++) {
      Thread thread = tarray[i];
      ClassLoader loader = thread.getContextClassLoader();
      String loaderName = (loader == null) ? "Default" : loader.getClass().getName();
      Thread.State state = thread.getState();
      long id = thread.getId();
      pw.print("   " + id + " " + thread.getName() + " " + state + " " + loaderName);
      if (thread == current) pw.println(" **** CURRENT ***");
      else pw.println();
    }

    int ngroups = g.activeGroupCount();
    ThreadGroup[] garray = new ThreadGroup[ngroups];
    int ng = g.enumerate(garray, false);
    for (int i = 0; i < ng; i++) {
      ThreadGroup nested = garray[i];
      showThreads(pw, nested, current);
    }
  }
  @Test
  public void testThreadDetails() {
    final AtomicReference<Thread> threadRef = new AtomicReference<Thread>();
    SingleThreadEventExecutor executor =
        new SingleThreadEventExecutor(null, Executors.newCachedThreadPool(), false) {
          @Override
          protected void run() {
            threadRef.set(Thread.currentThread());
            while (!confirmShutdown()) {
              Runnable task = takeTask();
              if (task != null) {
                task.run();
              }
            }
          }
        };
    ThreadProperties threadProperties = executor.threadProperties();
    Assert.assertSame(threadProperties, executor.threadProperties());

    Thread thread = threadRef.get();
    Assert.assertEquals(thread.getId(), threadProperties.id());
    Assert.assertEquals(thread.getName(), threadProperties.name());
    Assert.assertEquals(thread.getPriority(), threadProperties.priority());
    Assert.assertEquals(thread.getState(), threadProperties.state());
    Assert.assertEquals(thread.isAlive(), threadProperties.isAlive());
    Assert.assertEquals(thread.isDaemon(), threadProperties.isDaemon());
    Assert.assertEquals(thread.isInterrupted(), threadProperties.isInterrupted());
    Assert.assertTrue(threadProperties.stackTrace().length > 0);
    executor.shutdownGracefully();
  }
  /**
   * Update the information about completed thread that ran for runtime in milliseconds
   *
   * <p>This method updates all of the key timing and tracking information in the factory so that
   * thread can be retired. After this call the factory shouldn't have a pointer to the thread any
   * longer
   *
   * @param thread the thread whose information we are updating
   */
  @Ensures({"getTotalTime() >= old(getTotalTime())"})
  public synchronized void threadIsDone(final Thread thread) {
    nThreadsAnalyzed++;

    if (DEBUG) logger.warn("UpdateThreadInfo called");

    final long threadID = thread.getId();
    final ThreadInfo info = bean.getThreadInfo(thread.getId());
    final long totalTimeNano = bean.getThreadCpuTime(threadID);
    final long userTimeNano = bean.getThreadUserTime(threadID);
    final long systemTimeNano = totalTimeNano - userTimeNano;
    final long userTimeInMilliseconds = nanoToMilli(userTimeNano);
    final long systemTimeInMilliseconds = nanoToMilli(systemTimeNano);

    if (info != null) {
      if (DEBUG)
        logger.warn(
            "Updating thread with user runtime "
                + userTimeInMilliseconds
                + " and system runtime "
                + systemTimeInMilliseconds
                + " of which blocked "
                + info.getBlockedTime()
                + " and waiting "
                + info.getWaitedTime());
      incTimes(State.BLOCKING, info.getBlockedTime());
      incTimes(State.WAITING, info.getWaitedTime());
      incTimes(State.USER_CPU, userTimeInMilliseconds);
      incTimes(State.WAITING_FOR_IO, systemTimeInMilliseconds);
    }
  }
Exemplo n.º 4
0
 /*获取缩略图*/
 public Bitmap getThumbnail(
     ContentResolver contentResolver,
     long originalId,
     int kind,
     BitmapFactory.Options options,
     boolean isVideo) {
   Thread thread = Thread.currentThread();
   ThreadStatus threadStatus = getOrCreateThreadStatus(thread);
   if (!canThreadDecoding(thread)) {
     return null;
   }
   try {
     synchronized (threadStatus) {
       threadStatus.mThumbRequesting = true;
     }
     if (isVideo) {
       return MediaStore.Video.Thumbnails.getThumbnail(
           contentResolver, originalId, thread.getId(), kind, options);
     } else {
       return MediaStore.Images.Thumbnails.getThumbnail(
           contentResolver, originalId, thread.getId(), kind, options);
     }
   } finally {
     synchronized (threadStatus) {
       threadStatus.mThumbRequesting = false;
       threadStatus.notifyAll();
     }
   }
 }
  private static Set<Dependency> collectFromDependencyMonitor(
      ThreadMXBean bean, Serializable locality, Map<Long, ThreadInfo> threadInfos) {
    HashSet<Dependency> results = new HashSet<Dependency>();

    // Convert the held resources into serializable dependencies
    Set<Dependency<Serializable, Thread>> heldResources =
        DependencyMonitorManager.getHeldResources();
    for (Dependency<Serializable, Thread> dep : heldResources) {
      Thread thread = dep.getDependsOn();
      Serializable resource = dep.getDepender();
      ThreadInfo info = threadInfos.get(thread.getId());
      if (info == null) {
        info = bean.getThreadInfo(thread.getId());
      }
      if (info != null) {
        results.add(new Dependency(resource, new LocalThread(locality, info)));
      }
    }

    Set<Dependency<Thread, Serializable>> blockedThreads =
        DependencyMonitorManager.getBlockedThreads();

    // Convert the blocked threads into serializable dependencies
    for (Dependency<Thread, Serializable> dep : blockedThreads) {
      Thread thread = dep.getDepender();
      ThreadInfo info = threadInfos.get(thread.getId());
      if (info == null) {
        info = bean.getThreadInfo(thread.getId());
      }
      final Serializable resource = dep.getDependsOn();
      results.add(new Dependency(new LocalThread(locality, info), resource));
    }
    return results;
  }
Exemplo n.º 6
0
 /**
  * Constructor
  *
  * @param name
  * @param runnable
  * @param sleepPeriod
  */
 public ThreadRunner(String name, Runnable runnable, int sleepPeriod) {
   this.runner = new Thread(this);
   this.runner.setName(name + "-" + runner.getId());
   this.runner.setPriority(Thread.NORM_PRIORITY);
   this.runnable = runnable;
   this.sleepPeriod = sleepPeriod;
 }
  /// The watcher thread - from the Runnable interface.
  // This has to be pretty anal to avoid monitor lockup, lost
  // threads, etc.
  public synchronized void run() {
    Thread me = Thread.currentThread();
    me.setPriority(Thread.MAX_PRIORITY);

    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    startTimeInNs = threadMXBean.getCurrentThreadCpuTime();

    if (enabled.get()) {
      do {
        loop.set(false);
        try {
          wait(millis);
        } catch (InterruptedException e) {
        }
      } while (enabled.get() && loop.get());
    }

    if (enabled.get() && targetThread.isAlive()) {
      isDoneRunning.set(true);

      printThread();
      if (kill) {
        logger.warn(
            "Trying to kill thread with id:"
                + targetThread.getId()
                + " but did not as it can cause deadlocks etc.");
        // targetThread.interrupt();
        // targetThread.stop(); //Never kill thread - it can cause other problems
      }
      done();
      isDoneRunning.set(false);
    }
  }
Exemplo n.º 8
0
  public static void saveException(
      Throwable exception, Thread thread, CrashManagerListener listener) {
    final Date now = new Date();
    final Writer result = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(result);
    BufferedWriter writer = null;
    exception.printStackTrace(printWriter);

    try {
      // Create filename from a random uuid
      String filename = UUID.randomUUID().toString();
      String path = Constants.FILES_PATH + "/" + filename + ".stacktrace";
      Log.d(Constants.TAG, "Writing unhandled exception to: " + path);

      // Write the stacktrace to disk
      writer = new BufferedWriter(new FileWriter(path));

      // HockeyApp expects the package name in the first line!
      writer.write("Package: " + Constants.APP_PACKAGE + "\n");
      writer.write("Version Code: " + Constants.APP_VERSION + "\n");
      writer.write("Version Name: " + Constants.APP_VERSION_NAME + "\n");

      if ((listener == null) || (listener.includeDeviceData())) {
        writer.write("Android: " + Constants.ANDROID_VERSION + "\n");
        writer.write("Manufacturer: " + Constants.PHONE_MANUFACTURER + "\n");
        writer.write("Model: " + Constants.PHONE_MODEL + "\n");
      }

      if (thread != null && ((listener == null) || (listener.includeThreadDetails()))) {
        writer.write("Thread: " + thread.getName() + "-" + thread.getId() + "\n");
      }

      if (Constants.CRASH_IDENTIFIER != null
          && (listener == null || listener.includeDeviceIdentifier())) {
        writer.write("CrashReporter Key: " + Constants.CRASH_IDENTIFIER + "\n");
      }

      writer.write("Date: " + now + "\n");
      writer.write("\n");
      writer.write(result.toString());
      writer.flush();

      if (listener != null) {
        writeValueToFile(limitedString(listener.getUserID()), filename + ".user");
        writeValueToFile(limitedString(listener.getContact()), filename + ".contact");
        writeValueToFile(listener.getDescription(), filename + ".description");
      }
    } catch (Exception another) {
      Log.e(Constants.TAG, "Error saving exception stacktrace!\n", another);
    } finally {
      try {
        if (writer != null) {
          writer.close();
        }
      } catch (IOException e) {
        Log.e(Constants.TAG, "Error saving exception stacktrace!\n", e);
        e.printStackTrace();
      }
    }
  }
Exemplo n.º 9
0
  /**
   * Called when the surface changed size. When setPreserveEGLContextOnPause(true) is called in the
   * surface, this is called only once.
   */
  void onSurfaceCreated() {
    Log.v(TAG, "onSurfaceCreated");

    Thread currentThread = Thread.currentThread();

    // Reduce contention with other Android processes
    currentThread.setPriority(Thread.MAX_PRIORITY);

    // we know that the current thread is a GL one, so we store it to
    // prevent non-GL thread from calling GL functions
    mGLThreadID = currentThread.getId();
    mGlDeleterPtr = NativeGLDelete.ctor();

    // Evaluating anisotropic support on GL Thread
    String extensions = GLES20.glGetString(GLES20.GL_EXTENSIONS);
    isAnisotropicSupported = extensions.contains("GL_EXT_texture_filter_anisotropic");

    // Evaluating max anisotropic value if supported
    if (isAnisotropicSupported) {
      maxAnisotropicValue = NativeTextureParameters.getMaxAnisotropicValue();
    }

    mPreviousTimeNanos = GVRTime.getCurrentTime();

    /*
     * GL Initializations.
     */
    mRenderBundle = new GVRRenderBundle(this, mLensInfo);
    setMainScene(new GVRScene(this));
  }
Exemplo n.º 10
0
 @Override
 public Thread newThread(Runnable r) {
   Thread thread = new Thread(r);
   thread.setUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
   System.out.println("thread-id:" + thread.getId());
   return thread;
 }
 @Override
 public void uncaughtException(Thread t, Throwable e) {
   System.out.printf("The thread %s has thrown an Exception\n", t.getId());
   e.printStackTrace(System.out);
   System.out.printf("Terminating the rest of the Threads\n");
   interrupt();
 }
Exemplo n.º 12
0
  private void showDefaultInfo(ThreadGroup grp) {
    TreeSet<Thread> threadSet =
        new TreeSet<Thread>(
            new Comparator<Thread>() {
              @Override
              public int compare(Thread t1, Thread t2) {
                return Long.valueOf(t1.getId()).compareTo(t2.getId());
              }
            });
    findThreads(grp, threadSet);

    PrintWriter out = getOutput().getPrintWriter();
    for (final Thread thread : threadSet) {
      VmThread vmThread =
          AccessController.doPrivileged(
              new PrivilegedAction<VmThread>() {
                public VmThread run() {
                  return ThreadHelper.getVmThread(thread);
                }
              });
      out.println(
          " "
              + thread.getId()
              + SEPARATOR
              + thread.getName()
              + SEPARATOR
              + thread.getPriority()
              + SEPARATOR
              + vmThread.getThreadStateName());
    }
  }
Exemplo n.º 13
0
 void b(long l)
 {
     String s1;
     Thread thread;
     s1 = null;
     thread = Thread.currentThread();
     if (thread.getId() != l) goto _L2; else goto _L1
Exemplo n.º 14
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Thread ct = Thread.currentThread();
    // ct.setPriority(Thread.MAX_PRIORITY);
    uiThreadId = ct.getId();

    getWindow().setFlags(RhodesService.WINDOW_FLAGS, RhodesService.WINDOW_MASK);

    requestWindowFeature(Window.FEATURE_PROGRESS);
    getWindow().setFeatureInt(Window.FEATURE_PROGRESS, 10000);

    mSplashScreen = new SplashScreen(this);
    setMainView(mSplashScreen);

    Intent intent = new Intent(this, RhodesService.class);
    bindService(intent, this, Context.BIND_AUTO_CREATE);
    mBoundToService = true;

    mHandler = new Handler();
    mHandler.post(mSetup);

    sInstance = this;
  }
 private Thread findMatchingThread(ThreadInfo inf) {
   for (Thread thread : Thread.getAllStackTraces().keySet()) {
     if (thread.getId() == inf.getThreadId()) {
       return thread;
     }
   }
   throw new IllegalStateException("Deadlocked Thread not found");
 }
Exemplo n.º 16
0
  private static void writeThreadInfo(PrintWriter pw, Thread thread, State state) {

    pw.printf("Main: Id %d - %s\n", thread.getId(), thread.getName());
    pw.printf("Main:Prioity: %d\n", thread.getPriority());
    pw.printf("Main:Old state:%s\n", state);
    pw.printf("Main:New state:%s\n", thread.getState());
    pw.printf("Main:***********************************\n");
  }
Exemplo n.º 17
0
 public static String getThreadSignature() {
   Thread t = Thread.currentThread();
   long l = t.getId();
   String name = t.getName();
   long p = t.getPriority();
   String gname = t.getThreadGroup().getName();
   return (name + ":(id)" + l + ":(priority)" + p + ":(group)" + gname);
 }
Exemplo n.º 18
0
 public static void main(String[] args) {
   Thread thread = Thread.currentThread();
   System.out.println("Thread: " + thread);
   System.out.println("Thread Id: " + thread.getId());
   System.out.println("Thread Name: " + thread.getName());
   System.out.println("Thread Group: " + thread.getThreadGroup());
   System.out.println("Thread Priority: " + thread.getPriority());
 }
Exemplo n.º 19
0
  public boolean search() {

    Thread tread = java.lang.Thread.currentThread();
    java.lang.management.ThreadMXBean b = java.lang.management.ManagementFactory.getThreadMXBean();

    long startCPU = b.getThreadCpuTime(tread.getId());
    long startUser = b.getThreadUserTime(tread.getId());

    boolean result = store.consistency();
    System.out.println("*** consistency = " + result);

    Search<SetVar> label = new DepthFirstSearch<SetVar>();

    SelectChoicePoint<SetVar> select =
        new SimpleSelect<SetVar>(
            vars.toArray(new SetVar[vars.size()]),
            new MinLubCard<SetVar>(),
            new MaxGlbCard<SetVar>(),
            new IndomainSetMin<SetVar>());

    //	label.setSolutionListener(new SetSimpleSolutionListener<SetVar>());
    label.getSolutionListener().searchAll(false);
    label.getSolutionListener().recordSolutions(false);

    result = label.labeling(store, select);

    if (result) {
      System.out.println("*** Yes");
      for (int i = 0; i < weeks; i++) {
        for (int j = 0; j < groups; j++) {
          System.out.print(golferGroup[i][j].dom() + " ");
        }
        System.out.println();
      }
    } else System.out.println("*** No");

    System.out.println(
        "ThreadCpuTime = " + (b.getThreadCpuTime(tread.getId()) - startCPU) / (long) 1e+6 + "ms");
    System.out.println(
        "ThreadUserTime = "
            + (b.getThreadUserTime(tread.getId()) - startUser) / (long) 1e+6
            + "ms");

    return result;
  }
 /**
  * Main method of the class. It process the uncaught excpetions throwed in a Thread
  *
  * @param t The Thead than throws the Exception
  * @param e The Exception throwed
  */
 @Override
 public void uncaughtException(Thread t, Throwable e) {
   System.out.printf("An exception has been captured\n");
   System.out.printf("Thread: %s\n", t.getId());
   System.out.printf("Exception: %s: %s\n", e.getClass().getName(), e.getMessage());
   System.out.printf("Stack Trace: \n");
   e.printStackTrace(System.out);
   System.out.printf("Thread status: %s\n", t.getState());
 }
Exemplo n.º 21
0
 public String toString() {
   return "Looper ("
       + mThread.getName()
       + ", tid "
       + mThread.getId()
       + ") {"
       + Integer.toHexString(System.identityHashCode(this))
       + "}";
 }
 @Override
 public Thread newThread(Runnable r) {
   Thread t = new Thread(r, name + "-Thread_" + counter);
   counter++;
   stats.add(
       String.format(
           "Created thread %d with name %s on %s\n", t.getId(), t.getName(), new Date()));
   return t;
 }
 private void checkOnMediaCodecThread() {
   if (mediaCodecThread.getId() != Thread.currentThread().getId()) {
     throw new RuntimeException(
         "MediaCodecVideoDecoder previously operated on "
             + mediaCodecThread
             + " but is now called on "
             + Thread.currentThread());
   }
 }
Exemplo n.º 24
0
 public synchronized void cancelThreadDecoding(Thread thread, ContentResolver contentResolver) {
   ThreadStatus threadStatus = getOrCreateThreadStatus(thread);
   threadStatus.mState = State.CANCEL;
   if (threadStatus.mOptions != null) {
     threadStatus.mOptions.requestCancelDecode();
   }
   notifyAll();
   try {
     synchronized (threadStatus) {
       while (threadStatus.mThumbRequesting) {
         MediaStore.Images.Thumbnails.cancelThumbnailRequest(contentResolver, -1, thread.getId());
         MediaStore.Video.Thumbnails.cancelThumbnailRequest(contentResolver, -1, thread.getId());
         threadStatus.wait(200);
       }
     }
   } catch (Exception exception) {
   }
 }
Exemplo n.º 25
0
 /**
  * Method that creates a new Thread object using a Runnable object
  *
  * @param r: Runnable object to create the new Thread
  */
 public Thread newThread(Runnable r) {
   // Create the new Thread object
   Thread t = new Thread(r, name + "-Thread_" + counter);
   counter++;
   // Actualize the statistics of the factory
   stats.add(
       String.format(
           "Created thread %d with name %s on %s\n", t.getId(), t.getName(), new Date()));
   return t;
 }
  private static long getId(Thread thread) {
    if (threadIds == null) return thread.getId();

    Long threadId = threadIds.get(thread);
    if (threadId == null) {
      threadId = new Long(nextThreadId++);
      threadIds.put(thread, threadId);
    }
    return threadId.longValue();
  }
Exemplo n.º 27
0
 /**
  * - Check if the error simulator is still active. If it is not then the join operation is
  * running, making this unnecessary. - Loop through all the threads, checking if that thread's ID
  * is the ID of the thread that just ended. - If it is, remove it from the vector of threads and
  * break out of the loop.
  */
 public synchronized void callback(long id) {
   if (active.get()) {
     for (Thread t : threads) {
       if (t.getId() == id) {
         threads.remove(t);
         break;
       }
     }
   }
 }
Exemplo n.º 28
0
  /**
   * It parses the provided file and parsing parameters followed by problem solving.
   *
   * @param args parameters describing the flatzinc file containing the problem to be solved as well
   *     as options for problem solving.
   *     <p>TODO what are the conditions for different exceptions being thrown? Write little info
   *     below.
   * @throws ParseException
   * @throws TokenMgrError
   */
  public static void main(String[] args) {

    Options opt = new Options(args);

    if (opt.getVerbose())
      System.out.println("Flatzinc2JaCoP: compiling and executing " + args[args.length - 1]);

    Thread tread = java.lang.Thread.currentThread();
    java.lang.management.ThreadMXBean b = java.lang.management.ManagementFactory.getThreadMXBean();
    long startCPU = b.getThreadCpuTime(tread.getId());

    Parser parser = new Parser(opt.getFile());
    parser.setOptions(opt);

    try {

      parser.model();

    } catch (FailException e) {
      System.err.println(
          "=====UNSATISFIABLE====="); // "*** Evaluation of model resulted in fail.");
    } catch (ArithmeticException e) {
      System.err.println("*** Evaluation of model resulted in integer overflow.");
    } catch (ParseException e) {
      System.out.println("*** Parser exception " + e);
    } catch (TokenMgrError e) {
      System.out.println("*** Parser exception " + e);
    } catch (ArrayIndexOutOfBoundsException e) {
      System.out.println("*** Array out of bound exception " + e);
    } catch (OutOfMemoryError e) {
      System.out.println("*** Out of memory error; consider option -Xmx... for JVM");
    } catch (StackOverflowError e) {
      System.out.println("*** Stack overflow exception error; consider option -Xss... for JVM");
    }

    if (opt.getStatistics()) {
      System.out.println(
          "\nTotal CPU time : "
              + (b.getThreadCpuTime(tread.getId()) - startCPU) / (long) 1e+6
              + "ms");
    }
  }
Exemplo n.º 29
0
  /**
   * Main process
   *
   * @param args path to reach file we want to parse
   * @throws IOException
   * @throws FileAccessException args[0] = folder of application's dictionary view args[1] =
   *     plugin's name args[2] = folder where to find file
   */
  public static void main(String[] args) throws Exception {
    System.out.println("OK");

    final long time = System.currentTimeMillis();
    final String dico_path;
    int nbFiles = 0;
    plugin = "org.gumtree.data.soleil.NxsFactory";

    // Dictionary path
    if (args.length > 0) {
      dico_path = args[0];
      Factory.setDictionariesFolder(dico_path);
    }

    // Setting plug-in to use
    if (args.length > 1) {
      plugin = args[1];
    }

    if (args.length > 2) {
      sample_path = args[2];
    }
    int i = 0;
    File folder = new File(sample_path);
    if (folder.exists()) {
      for (File sample : folder.listFiles()) {

        Runnable test = new Process(sample);
        Thread thread = new Thread(test);
        thread.start();
        poolThread.add(thread);
        if (!useThreads) {
          thread.join();
        }
        System.out.println(thread.getId() + "-------> " + sample.getName());

        if (true) return;

        // test.run();
      }
    }

    if (useThreads) {
      for (Thread t : poolThread) {
        t.join();
      }
    }
    i++;
    // IFactory factory = Factory.getFactory(plugin);
    // TestArrayManual.testManuallyCreatedArrays(factory);
    System.out.println(
        "Total execution time: " + ((System.currentTimeMillis() - time) / 1000.) + "s");
    System.out.println("Nb files tested: " + nbFiles);
  }
Exemplo n.º 30
0
 /** Start the IMS connection */
 private synchronized void startImsConnection() {
   if (mImsPollingThreadId >= 0) {
     return;
   }
   if (sLogger.isActivated()) {
     sLogger.info("Start the IMS connection manager");
   }
   mImsPollingThread = new Thread(this);
   mImsPollingThreadId = mImsPollingThread.getId();
   mImsPollingThread.start();
 }