/**
   * Instantiates a new transaction manager.
   *
   * @param parentCollection thats uses this manager
   */
  public TransactionManager(final TimeoutCollection<V> parentCollection) {
    this.parentCollection = parentCollection;

    txnRemovalQueue = new LinkedBlockingQueue<Transaction<V>>();
    txnTimeoutQueue = new TimeoutQueue<Transaction<V>>(txnRemovalQueue);
    final Thread txnHeadReader =
        new Thread(
            new Runnable() {
              public void run() {
                //noinspection InfiniteLoopStatement
                while (true) {
                  try {

                    final Transaction<V> txn = txnRemovalQueue.take();

                    try {
                      abortTxn(txn.getTxnId());

                    } catch (final TransactionException e) {
                      // TODO need to get this exception out??
                      e
                          .printStackTrace(); // To change body of catch statement use File |
                                              // Settings | File Templates.
                    }

                  } catch (final InterruptedException e) {
                    Thread.currentThread().interrupt();
                  }
                }
              }
            });
    txnHeadReader.setDaemon(true);
    txnHeadReader.start();
  }
Esempio n. 2
1
  // --------------------------------actionConnect------------------------------
  private void actionConnect() {
    if (oParty == null) {
      JOptionPane.showMessageDialog(frame, "Make a party before trying to connect.");
      return;
    }

    String[] oResults = (String[]) DialogManager.show(DialogManager.CONNECT, frame);

    if (oResults[DialogManager.RETURN_IP].equals("cancel")) return;

    lblStatus3.setText("Connecting...");
    try {
      oConn.connect(
          oResults[DialogManager.RETURN_IP], Integer.parseInt(oResults[DialogManager.RETURN_PORT]));
    } catch (UnknownHostException e) {
      JOptionPane.showMessageDialog(
          frame,
          "The IP of the host cannot be determined.",
          "Unknown Host Exception",
          JOptionPane.ERROR_MESSAGE);
      frame.repaint();
      return;
    } catch (IOException e) {
      JOptionPane.showMessageDialog(
          frame, e.getMessage(), "Input/Output Exception", JOptionPane.ERROR_MESSAGE);
      frame.repaint();
      return;
    }
    echo("Connected to opponent!");

    tConn = new Thread(oConn, "conn");
    tConn.start();
    tMain = new Thread(this, "main");
    tMain.start();
  }
Esempio n. 3
1
  public void testParallelOneStore() throws Exception {
    final List<Exception> exceptions = new ArrayList<Exception>();

    List<Thread> threads = new ArrayList<Thread>();

    for (int i = 9000; i < 9020; i++) {
      final int index = i;
      Thread thread =
          new Thread() {
            public void run() {
              try {
                parallelStoreRetrieve(metaStore, index);
              } catch (Exception e) {
                exceptions.add(e);
              }
            }
          };
      threads.add(thread);
      thread.start();
    }

    for (Thread thread : threads) {
      thread.join();
    }

    if (!exceptions.isEmpty()) {
      for (Exception e : exceptions) {
        e.printStackTrace(System.err);
      }
      fail(exceptions.size() + " exceptions encountered during parallel store/retrieve");
    }
  }
Esempio n. 4
1
 /** 初始化 */
 public void init(Context context) {
   this.context = context;
   // 获取系统默认的UncaughtException处理器
   mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
   // 设置该CrashHandler为程序的默认处理器
   Thread.setDefaultUncaughtExceptionHandler(this);
 }
 @Override
 public Thread newThread(Runnable r) {
   Thread thread = new Thread(r, "ProgressThread");
   thread.setDaemon(true);
   thread.setPriority(Thread.MIN_PRIORITY);
   return thread;
 }
 /**
  * Load fixtures and send it to the {@link SolrServer}.
  *
  * @param server The solr server.
  * @param core The core's name.
  * @param fixturesDir The fixtures directory.
  * @param async True for using a thread.
  */
 private static void populate(
     final SolrServer server, final String core, final File fixturesDir, final boolean async) {
   final Collection<File> xmlFiles = FileUtils.listFiles(fixturesDir, new String[] {"xml"}, true);
   if (xmlFiles.size() > 0) {
     Runnable post =
         new Runnable() {
           @Override
           public void run() {
             try {
               for (File xmlFile : xmlFiles) {
                 logger.info("[{}]: sending: {}...", core, xmlFile);
                 // Ensure it's in UTF-8 encoding
                 Reader reader = new InputStreamReader(new FileInputStream(xmlFile), "UTF-8");
                 String body = IOUtils.toString(reader);
                 SolrRequest request = new DirectXmlRequest("/update", body);
                 /** Post the document to the Index */
                 request.process(server);
                 IOUtils.closeQuietly(reader);
               }
               // Commit the changes
               server.commit();
             } catch (Exception ex) {
               logger.error("Unable to initialize data", ex);
             }
           }
         };
     if (async) {
       Thread thread = new Thread(post, core + "-postData");
       thread.setDaemon(true);
       thread.start();
     } else {
       post.run();
     }
   }
 }
        @Override
        public void run() {
          // The service makes use of an explicit Thread instead of a Handler because with the
          // Threat the code is executed more synchronously.
          // However the ViewGraphic is drawed with a Handler because the drawing code must be
          // executed in the UI thread.
          Thread thisThread = Thread.currentThread();
          while (readThread == thisThread) {
            read();
            try {
              Thread.sleep(intervalRead);
              /*					synchronized (this) {
              	while (readThread == thisThread && threadSuspended)
              		wait();
              }*/
            } catch (InterruptedException e) {
              break;
            }

            // The Runnable can be suspended and resumed with the below code:
            //		        threadSuspended = !threadSuspended;
            //		        if (!threadSuspended)
            //		            notify();
          }
        }
  public static void main(String[] args) {

    for (int i = 0; i < Length; i++) {
      Thread t = new Thread(new MyRunnable());
      t.start();
    }
  }
Esempio n. 9
1
 private void startClientMessageReader(final Queue queue, Socket clientSocket) {
   try {
     InputStream ipStream = clientSocket.getInputStream();
     final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(ipStream));
     final ClientDetails clientDetails =
         new ClientDetails(readUserName(bufferedReader), clientSocket);
     Thread clientReaderThread =
         new Thread(
             new Runnable() {
               public void run() {
                 ClientRegistry clientRegistry = serverContext.getClientRegistry();
                 clientRegistry.register(clientDetails);
                 LOGGER.info("{} connected", clientDetails.getUserName());
                 try {
                   new ClientMessageReader(queue, clientDetails, serverContext)
                       .read(bufferedReader);
                 } finally {
                   clientRegistry.deregister(clientDetails);
                   LOGGER.info("{} disconnected", clientDetails.getUserName());
                 }
               }
             });
     clientReaderThread.setName("Client Reader - " + clientDetails.getUserName());
     clientReaderThread.start();
     threadList.add(clientReaderThread);
   } catch (IOException e) {
     throw new EndpointException("I/O Error while creating stream", e);
   }
 }
Esempio n. 10
0
  @Test(priority = 2)
  public void AssignUpr() throws Exception {
    action.driver.navigate().refresh();
    // Click on tenant Management Link
    action.ClickLink(locator.getProperty("Tenant_Management"));
    action.WaitForTitle(locator.getProperty("Multi-Tenancy_Management"));
    action.VerifyTitle(locator.getProperty("Multi-Tenancy_Management"));
    action.SwithchFrame("iframe0");
    action.ClickElement(locator.getProperty("Tenanttree3"));
    Thread.sleep(1000);
    action.ClickLink(input.getProperty("site1"));
    action.ClickLink(locator.getProperty("User_Provisioning_Rule"));
    action.ClickButton(locator.getProperty("Tenantedit"));
    Thread.sleep(1000);
    // Select the Upr From table
    action.ClickButton(locator.getProperty("Tenantuprbtn0"));
    Thread.sleep(1000);
    // Click on Commit button
    action.ClickButton(locator.getProperty("Commit"));
    Thread.sleep(1000);

    action.WaitForTitle(locator.getProperty("Multi-Tenancy_Management"));
    action.VerifyTitle(locator.getProperty("Multi-Tenancy_Management"));
    Thread.sleep(2000);
    action.VerifyStringValue(
        "site1 is updated successfully. Refresh the tree to see updated node.");
  }
Esempio n. 11
0
 @Override
 public void run() {
   /* Legacy UDP location manager daemon.
    */
   DatagramPacket packet;
   while (!Thread.currentThread().isInterrupted()) {
     try {
       packet = new DatagramPacket(new byte[1024], 1024);
       socket.receive(packet);
     } catch (SocketException e) {
       if (!Thread.currentThread().isInterrupted()) {
         LOGGER.warn("Exception in Server receive loop (exiting)", e);
       }
       break;
     } catch (Exception ie) {
       LOGGER.warn("Exception in Server receive loop (exiting)", ie);
       break;
     }
     try {
       process(packet);
       socket.send(packet);
     } catch (Exception se) {
       LOGGER.warn("Exception in send ", se);
     }
   }
   socket.close();
 }
 /*
 This test will update the Synapse configuration
  */
 public void updateSynapseConfig() throws Exception {
   selenium.click("link=Synapse");
   Thread.sleep(2000);
   selenium.click("updateConfig");
   Thread.sleep(10000);
   selenium.click("//button[@type='button']");
 }
Esempio n. 13
0
 /**
  * Enable sharing of the class-loader with 3rd party (e.g. digester).
  *
  * @return the class-loader user be the helper.
  */
 public ClassLoader getClassLoader() {
   log.debug(
       "Class classloader: {} Thread classloader: {}",
       this.getClass().getClassLoader(),
       Thread.currentThread().getContextClassLoader());
   return Thread.currentThread().getContextClassLoader();
 }
Esempio n. 14
0
 public void run() {
   try {
     Thread.sleep(Long.MAX_VALUE);
   } catch (InterruptedException e) {
     System.out.println("[" + Thread.currentThread().getName() + "] Interrupted by exception!");
   }
 }
Esempio n. 15
0
 @Override
 public void onCreate() {
   Log.v("MyAlarmServiceログ", "Create");
   Thread thr = new Thread(null, mTask, "MyAlarmServiceThread");
   thr.start();
   Log.v("MyAlarmServiceログ", "スレッド開始");
 }
  public boolean request(Object soaprequest) {
    if (!checkSoapMemberVariable()) return false;

    ServiceRequest req =
        new ServiceRequest(
            this.ServerUrl,
            this.SoapAction,
            this.NameSpace,
            this.MethodName,
            this.SoapVersion,
            this.DotNet,
            (SoapObject) soaprequest);
    Thread thread = new Thread(req);

    try {
      thread.start();
      thread.join();
    } catch (Exception e) {
      this.Response = null;
      e.printStackTrace();
      return false;
    }

    this.Response = req.getResponse();
    if (this.Response == null) return false;
    return true;
  }
  /** {@inheritDoc} */
  @SuppressWarnings("deprecation")
  public void stop() {
    this.isRunning_ = false;

    if (this.isListening_ == false) {
      try {
        //  通信用ポートBind待ち状態のために、割り込みを行う
        Thread acceptThread = this.acceptThread_;
        if (acceptThread != null) {
          acceptThread.interrupt();
        }
      } catch (Exception ex) {
        LOGGER.warn(ex);
      }
    }

    if (this.isListening_) {
      // 待ち受けソケットを閉じることにより、accept()でSocketExceptionが
      // 発生し、待ち受けスレッドが停止する。
      if (this.objServerSocket_ != null) {
        try {
          this.objServerSocket_.close();
        } catch (Exception ex) {
          LOGGER.warn(ex);
        }
      }

      this.isListening_ = false;
    }
  }
Esempio n. 18
0
  private static void check(MimeType type, String str) throws Exception {
    References references;

    Node node = WORLD.getTemp().createTempFile();
    node.writeString(str);
    references = References.create(type, true, node);
    references.readBytes();
    node.deleteFile();

    System.gc();
    Thread.sleep(1000);

    System.out.println("Startup done");
    Thread.sleep(20000);
    System.out.println("computing ...");

    node = WORLD.getTemp().createTempFile();
    node.writeString(str);
    references = References.create(type, true, node);
    references.readBytes();
    node.deleteFile();

    System.out.println("busy wait to keep references");
    for (; ; ) ;
  }
  @Test(timeout = 2000)
  public void testCleanupQueueClosesFilesystem()
      throws IOException, InterruptedException, NoSuchFieldException, IllegalAccessException {
    Configuration conf = new Configuration();
    File file = new File("afile.txt");
    file.createNewFile();
    Path path = new Path(file.getAbsoluteFile().toURI());

    FileSystem.get(conf);
    Assert.assertEquals(1, getFileSystemCacheSize());

    // With UGI, should close FileSystem
    CleanupQueue cleanupQueue = new CleanupQueue();
    PathDeletionContext context =
        new PathDeletionContext(path, conf, UserGroupInformation.getLoginUser(), null, null);
    cleanupQueue.addToQueue(context);

    while (getFileSystemCacheSize() > 0) {
      Thread.sleep(100);
    }

    file.createNewFile();
    FileSystem.get(conf);
    Assert.assertEquals(1, getFileSystemCacheSize());

    // Without UGI, should not close FileSystem
    context = new PathDeletionContext(path, conf);
    cleanupQueue.addToQueue(context);

    while (file.exists()) {
      Thread.sleep(100);
    }
    Assert.assertEquals(1, getFileSystemCacheSize());
  }
  public synchronized NetworkStatsItemBean[] getSearchItems() {
    if (null == queryString) {
      return null;
    }
    if (!isFreshSearch) {
      return searchItemBeans;
    }

    try {
      ItemType searchItems[] = getSearchResults(queryString);
      if (null == searchItems) {
        return null;
      }
      searchItemBeans = new NetworkStatsItemBean[searchItems.length];

      for (int i = 0; i < searchItems.length; i++) {
        searchItemBeans[i] = new NetworkStatsItemBean(searchItems[i]);
      }
      isFreshSearch = false;
      Thread t = new Thread(new NetworkStatsItemDetailer(this, searchItemBeans));
      t.start();
      return searchItemBeans;
    } catch (Exception e) {
      if (log.isErrorEnabled()) {
        log.error("Failed to read the available search items because of " + e);
      }
    }
    return null;
  }
Esempio n. 21
0
 @Override
 protected void afterExecute(Runnable r, Throwable t) {
   super.afterExecute(r, t);
   Thread thread = (Thread) r;
   runningThreadNames.remove(thread.getName());
   logger.debug("{} ===================> Finished.", thread.getName());
 }
  public void testSearchUser() {
    NetworkDataManager ndm = new NetworkDataManager();
    User user = new User();
    User user2;
    user.setName("Connor");
    user.setUserAddress("1021");
    user.setUserName("ccdunn");
    user.setUserEmail("*****@*****.**");
    user.addFriend("gbullock");

    ndm.saveUser(user);

    try {
      Thread.sleep(500);
    } catch (Exception e) {
      e.printStackTrace();
    }

    assertTrue("Could not find the user", ndm.searchUser(user.getUserName()));

    assertFalse("Found a user that doesnt exist!", ndm.searchUser("NotExistingUser"));

    ndm.deleteUser(user.getUserName());

    try {
      Thread.sleep(500);
    } catch (Exception e) {
      e.printStackTrace();
    }

    assertFalse("Still finding user that should be deleted...", ndm.searchUser(user.getUserName()));
  }
  @Override
  protected Statement methodBlock(FrameworkMethod frameworkMethod) {
    Thread currentThread = Thread.currentThread();

    ClassLoader contextClassLoader = currentThread.getContextClassLoader();

    PortalClassLoaderUtil.setClassLoader(contextClassLoader);

    TestClass testClass = getTestClass();

    List<FrameworkMethod> beforeFrameworkMethods = testClass.getAnnotatedMethods(Before.class);

    List<FrameworkMethod> afterFrameworkMethods = testClass.getAnnotatedMethods(After.class);

    List<String> arguments = createArguments(frameworkMethod);

    Class<?> clazz = testClass.getJavaClass();

    return new RunInNewJVMStatment(
        _classPath,
        arguments,
        clazz,
        beforeFrameworkMethods,
        frameworkMethod,
        afterFrameworkMethods);
  }
  /**
   * A method that spawns an ILDS object and calls its solve method. If other algorithms were used,
   * this would be a good place to call their solve methods.
   */
  public void solve() {
    /* Create a depth first search instance */
    ILDS dfs = new ILDS(students, fileIO.getGroupTimes());

    if (timeout != 0) {
      Thread thread =
          new Thread() {
            public void run() {
              Timer timer = new Timer();
              timer.schedule(
                  new TimerTask() {
                    @Override
                    public void run() {
                      dfs.end();
                    }
                  },
                  timeout);
            }
          };
      thread.start();
    }

    /* Solve and print the solution */
    dfs.solve();
    solutionCost = dfs.getSolutionCost();
    printStudentSolution(dfs.getSolution());
  }
Esempio n. 25
0
  /** run do the work. */
  public void run() {
    int percent = 0;
    String msg = "";
    System.out.println(
        "SimpleWorker.run : Thread " + Thread.currentThread().getName() + " started");

    eventQueue = Toolkit.getDefaultToolkit().getSystemEventQueue();

    //        while (running) {
    //            count++;
    //            if (count >= MAXWORK) {
    //                running = false;
    //            }
    //
    //            msg = "Message from " + Thread.currentThread().getName()
    //                    + " : " + count;
    //
    //            eventQueue.postEvent(new EventSearchWorker(target, msg, count));
    //
    //            try {
    //                this.sleep(800);
    //            } catch (Exception e) {
    //                System.out.println("E:run : " + e.toString());
    //            }
    //        }
    //        eventQueue.postEvent(new EventSearchWorker(target, "deneme\n", count));
    search(searchEngine);
    target.dispatchEvent(
        new EventSearchWorker(target, "", count, this.searchEngine.getName() + " completed.."));

    //        eventQueue.postEvent(new EventSearchWorker(target, "Work done..", count));
    System.out.println("SimpleWorker.run : Thread " + Thread.currentThread().getName() + " stoped");
  } // run
Esempio n. 26
0
  public synchronized String format(LogRecord record) {
    StringBuffer sb = new StringBuffer();
    date.setTime(record.getMillis() + timeDiff);
    sb.append(dFormat.format(date));
    if (isShowingThreads) {
      Thread currentThread = Thread.currentThread();
      if (currentThread != lastThread) {
        lastThread = currentThread;
        lastThreadName = currentThread.getName();
      }
      sb.append(" [").append(lastThreadName).append(']');
    }
    sb.append(' ')
        .append(record.getLevel())
        .append(' ')
        .append(getAliasFor(record.getLoggerName()))
        .append('|')
        .append(record.getMessage())
        .append(EOL);

    if (record.getThrown() != null) {
      try {
        StringWriter out = new StringWriter();
        PrintWriter pout = new PrintWriter(out);
        record.getThrown().printStackTrace(pout);
        pout.close();
        sb.append(out.toString());
      } catch (Exception e) {
        // Ignore any errors while extracting stack trace
      }
    }

    return sb.toString();
  }
Esempio n. 27
0
 /**
  * A new method that interrupts the worker thread. Call this method to force the worker to stop
  * what it's doing.
  */
 public void interrupt() {
   Thread t = threadVar.get();
   if (t != null) {
     t.interrupt();
   }
   threadVar.clear();
 }
  private void waitUntilServerIsRunning(boolean reconnect)
      throws IOException, InterruptedException, TimeoutException {

    Thread.sleep(500); // this value is taken from implementation of CLI "reload"

    if (reconnect) {
      client.reconnect(timeoutInSeconds);
    }

    long endTime = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(timeoutInSeconds);
    while (System.currentTimeMillis() < endTime) {
      try {
        if (isServerRunning()) {
          break;
        }
      } catch (Throwable ignored) {
        // server is probably down, will retry
      }

      Thread.sleep(200); // this value is completely arbitrary
    }

    boolean running = false;
    try {
      running = isServerRunning();
    } catch (Throwable ignored) {
      // server probably down
    }
    if (!running) {
      throw new TimeoutException("Waiting for server timed out");
    }
  }
Esempio n. 29
0
  private synchronized void addSocket(Socket socket) {

    sockets.add(socket);
    ClientConnection cl = new ClientConnection(socket);
    Thread t = new Thread(cl);
    t.start();
  }
Esempio n. 30
0
  private void startButtonActionPerformed(
      java.awt.event.ActionEvent evt) { // GEN-FIRST:event_startButtonActionPerformed
    Thread starterThread = new Thread(new StartServer());
    starterThread.start();

    serverStatus.append("Server started....\n");
  } // GEN-LAST:event_startButtonActionPerformed