Esempio n. 1
1
 void start() {
   if (t == null) {
     t = new Thread(this, "UDP.OutgoingPacketHandler thread");
     t.setDaemon(true);
     t.start();
   }
 }
Esempio n. 2
0
  /**
   * Test batched prepared statement concurrency. Batch prepares must not disappear between the
   * moment when they were created and when they are executed.
   */
  public void testConcurrentBatching() throws Exception {
    // Create a connection with a batch size of 1. This should cause prepares and actual batch
    // execution to become
    // interspersed (if correct synchronization is not in place) and greatly increase the chance of
    // prepares
    // being rolled back before getting executed.
    Properties props = new Properties();
    props.setProperty(Messages.get(net.sourceforge.jtds.jdbc.Driver.BATCHSIZE), "1");
    props.setProperty(
        Messages.get(net.sourceforge.jtds.jdbc.Driver.PREPARESQL),
        String.valueOf(TdsCore.TEMPORARY_STORED_PROCEDURES));
    Connection con = getConnection(props);

    try {
      Statement stmt = con.createStatement();
      stmt.execute(
          "create table #testConcurrentBatch (v1 int, v2 int, v3 int, v4 int, v5 int, v6 int)");
      stmt.close();

      Vector exceptions = new Vector();
      con.setAutoCommit(false);

      Thread t1 = new ConcurrentBatchingHelper(con, exceptions);
      Thread t2 = new ConcurrentBatchingHelper(con, exceptions);
      t1.start();
      t2.start();
      t1.join();
      t2.join();

      assertEquals(0, exceptions.size());
    } finally {
      con.close();
    }
  }
Esempio n. 3
0
 /** Redirect a VMs output and error streams to System.out and System.err */
 protected void redirectStreams(VirtualMachine vm) {
   MessageSiphon ms = new MessageSiphon(process.getErrorStream(), this);
   errThread = ms.getThread();
   outThread = new StreamRedirectThread("VM output reader", process.getInputStream(), System.out);
   errThread.start();
   outThread.start();
 }
Esempio n. 4
0
  public static void main(String[] args) throws Exception {
    int minTokenCount = 5;
    File corpusFile = new File(args[0]);
    CharSequence[] articleTexts = LdaWormbase.readCorpus(corpusFile);
    SymbolTable symbolTable = new MapSymbolTable();
    TokenizerFactory tokenizerFactory = LdaWormbase.WORMBASE_TOKENIZER_FACTORY;
    int[][] docTokens =
        LatentDirichletAllocation.tokenizeDocuments(
            articleTexts, tokenizerFactory, symbolTable, minTokenCount);

    LdaRunnable runnable1 =
        new LdaRunnable(docTokens, new LdaReportingHandler(symbolTable), new Random());

    LdaRunnable runnable2 =
        new LdaRunnable(docTokens, new LdaReportingHandler(symbolTable), new Random());

    Thread thread1 = new Thread(runnable1);
    Thread thread2 = new Thread(runnable2);

    thread1.start();
    thread2.start();

    thread1.join();
    thread2.join();

    LatentDirichletAllocation lda0 = runnable1.mLda;

    LatentDirichletAllocation lda1 = runnable2.mLda;

    System.out.println("\nComputing Greedy Aligned Symmetrized KL Divergences");
    double[] scores = similarity(lda0, lda1);
    for (int i = 0; i < scores.length; ++i) System.out.printf("%4d %15.3f\n", i, scores[i]);
  }
Esempio n. 5
0
  @Test
  public void testOfferPoll() throws IOException, InterruptedException {

    final IQueue q = client.getQueue(queueForTestOfferPoll);

    for (int i = 0; i < 10; i++) {
      boolean result = q.offer("item");
      if (i < maxSizeForQueue) {
        assertTrue(result);
      } else {
        assertFalse(result);
      }
    }
    assertEquals(maxSizeForQueue, q.size());

    final Thread t1 =
        new Thread() {
          public void run() {
            try {
              Thread.sleep(2 * 1000);
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
            q.poll();
          }
        };
    t1.start();

    boolean result = q.offer("item", 5, TimeUnit.SECONDS);
    assertTrue(result);

    for (int i = 0; i < 10; i++) {
      Object o = q.poll();
      if (i < maxSizeForQueue) {
        assertNotNull(o);
      } else {
        assertNull(o);
      }
    }
    assertEquals(0, q.size());

    final Thread t2 =
        new Thread() {
          public void run() {
            try {
              Thread.sleep(2 * 1000);
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
            q.offer("item1");
          }
        };
    t2.start();

    Object o = q.poll(5, TimeUnit.SECONDS);
    assertEquals("item1", o);
    t1.join(10000);
    t2.join(10000);
  }
  public SetIfModifiedSince() throws Exception {

    serverSock = new ServerSocket(0);
    int port = serverSock.getLocalPort();

    Thread thr = new Thread(this);
    thr.start();

    Date date = new Date(new Date().getTime() - 1440000); // this time yesterday
    URL url;
    HttpURLConnection con;

    // url = new URL(args[0]);
    url = new URL("http://localhost:" + String.valueOf(port) + "/anything");
    con = (HttpURLConnection) url.openConnection();

    con.setIfModifiedSince(date.getTime());
    con.connect();
    int ret = con.getResponseCode();

    if (ret == 304) {
      System.out.println("Success!");
    } else {
      throw new RuntimeException(
          "Test failed! Http return code using setIfModified method is:"
              + ret
              + "\nNOTE:some web servers are not implemented according to RFC, thus a failed test does not necessarily indicate a bug in setIfModifiedSince method");
    }
  }
Esempio n. 7
0
    @Override
    public void actionPerformed(ActionEvent e) {
      Frame frame = getFrame();
      JFileChooser chooser = new JFileChooser();
      int ret = chooser.showOpenDialog(frame);

      if (ret != JFileChooser.APPROVE_OPTION) {
        return;
      }

      File f = chooser.getSelectedFile();
      if (f.isFile() && f.canRead()) {
        Document oldDoc = getEditor().getDocument();
        if (oldDoc != null) {
          oldDoc.removeUndoableEditListener(undoHandler);
        }
        if (elementTreePanel != null) {
          elementTreePanel.setEditor(null);
        }
        getEditor().setDocument(new PlainDocument());
        frame.setTitle(f.getName());
        Thread loader = new FileLoader(f, editor.getDocument());
        loader.start();
      } else {
        JOptionPane.showMessageDialog(
            getFrame(),
            "Could not open file: " + f,
            "Error opening file",
            JOptionPane.ERROR_MESSAGE);
      }
    }
Esempio n. 8
0
  /**
   * This starts the layout thread, it does not run before this. Note this is a background check it
   * doesn't stop when done it just sleeps until it gets more work.
   */
  public void start() {

    if (controller != null && !runner.isAlive() && !pauseState) {
      active = true;
      runner.start();
    }
  }
Esempio n. 9
0
    /**
     * @param views Guaranteed to be non-null and to have >= 2 members, or else this thread would
     *     not be started
     */
    public synchronized void start(Map<Address, View> views) {
      if (thread == null || thread.isAlive()) {
        this.coords.clear();

        // now remove all members which don't have us in their view, so RPCs won't block (e.g.
        // FLUSH)
        // https://jira.jboss.org/browse/JGRP-1061
        sanitizeViews(views);

        // Add all different coordinators of the views into the hashmap and sets their members:
        Collection<Address> coordinators = Util.determineMergeCoords(views);
        for (Address coord : coordinators) {
          View view = views.get(coord);
          if (view != null) this.coords.put(coord, new ArrayList<Address>(view.getMembers()));
        }

        // For the merge participants which are not coordinator, we simply add them, and the
        // associated
        // membership list consists only of themselves
        Collection<Address> merge_participants = Util.determineMergeParticipants(views);
        merge_participants.removeAll(coordinators);
        for (Address merge_participant : merge_participants) {
          Collection<Address> tmp = new ArrayList<Address>();
          tmp.add(merge_participant);
          coords.putIfAbsent(merge_participant, tmp);
        }

        thread = gms.getThreadFactory().newThread(this, "MergeTask");
        thread.setDaemon(true);
        thread.start();
      }
    }
 void asyncUpdate() throws BundleException {
   if (getEquinoxContainer().getConfiguration().getDebug().DEBUG_SYSTEM_BUNDLE) {
     Debug.printStackTrace(
         new Exception("Framework has been requested to update (restart).")); // $NON-NLS-1$
   }
   lockStateChange(ModuleEvent.UPDATED);
   try {
     if (Module.ACTIVE_SET.contains(getState())) {
       Thread t =
           new Thread(
               new Runnable() {
                 @Override
                 public void run() {
                   try {
                     update();
                   } catch (Throwable e) {
                     SystemBundle.this
                         .getEquinoxContainer()
                         .getLogServices()
                         .log(
                             EquinoxContainer.NAME,
                             FrameworkLogEntry.ERROR,
                             "Error updating the framework.",
                             e); //$NON-NLS-1$
                   }
                 }
               },
               "Framework update"); //$NON-NLS-1$
       t.start();
     }
   } finally {
     unlockStateChange(ModuleEvent.UPDATED);
   }
 }
 public void initialize() {
   // Start session monitor.
   monitor = new PasswordManagementMonitor(this);
   Thread t = new Thread(monitor);
   t.setName("JOSSOPasswordManagementMonitor");
   t.start();
 }
  /** Second part of debugger start procedure. */
  private void startDebugger() {
    threadManager = new ThreadManager(this);

    setBreakpoints();
    updateWatches();
    println(bundle.getString("CTL_Debugger_running"), STL_OUT);
    setDebuggerState(DEBUGGER_RUNNING);

    virtualMachine.resume();

    // start refresh thread .................................................
    if (debuggerThread != null) debuggerThread.stop();
    debuggerThread =
        new Thread(
            new Runnable() {
              public void run() {
                for (; ; ) {
                  try {
                    Thread.sleep(5000);
                  } catch (InterruptedException ex) {
                  }
                  if (getState() == DEBUGGER_RUNNING) threadGroup.refresh();
                }
              }
            },
            "Debugger refresh thread"); // NOI18N
    debuggerThread.setPriority(Thread.MIN_PRIORITY);
    debuggerThread.start();
  }
Esempio n. 13
0
  public void onRemovePressed(final ContributedLibrary lib) {
    boolean managedByIndex = indexer.getIndex().getLibraries().contains(lib);

    if (!managedByIndex) {
      int chosenOption = JOptionPane.showConfirmDialog(this, _("This library is not listed on Library Manager. You won't be able to resinstall it from here.\nAre you sure you want to delete it?"), _("Please confirm library deletion"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
      if (chosenOption != JOptionPane.YES_OPTION) {
        return;
      }
    }

    clearErrorMessage();
    installerThread = new Thread(new Runnable() {
      @Override
      public void run() {
        try {
          setProgressVisible(true, _("Removing..."));
          installer.remove(lib);
          onIndexesUpdated(); // TODO: Do a better job in refreshing only the needed element
          //getContribModel().updateLibrary(lib);
        } catch (Exception e) {
          throw new RuntimeException(e);
        } finally {
          setProgressVisible(false, "");
        }
      }
    });
    installerThread.setUncaughtExceptionHandler(new InstallerJDialogUncaughtExceptionHandler(this, noConnectionErrorMessage));
    installerThread.start();
  }
Esempio n. 14
0
  // Do some simple concurrent testing
  public void testConcurrentSimple() throws InterruptedException {
    final NonBlockingIdentityHashMap<String, String> nbhm =
        new NonBlockingIdentityHashMap<String, String>();
    final String[] keys = new String[20000];
    for (int i = 0; i < 20000; i++) keys[i] = "k" + i;

    // In 2 threads, add & remove even & odd elements concurrently
    Thread t1 =
        new Thread() {
          public void run() {
            work_helper(nbhm, "T1", 1, keys);
          }
        };
    t1.start();
    work_helper(nbhm, "T0", 0, keys);
    t1.join();

    // In the end, all members should be removed
    StringBuffer buf = new StringBuffer();
    buf.append("Should be emptyset but has these elements: {");
    boolean found = false;
    for (String x : nbhm.keySet()) {
      buf.append(" ").append(x);
      found = true;
    }
    if (found) System.out.println(buf + " }");
    assertThat("concurrent size=0", nbhm.size(), is(0));
    for (String x : nbhm.keySet()) {
      assertTrue("No elements so never get here", false);
    }
  }
Esempio n. 15
0
  private static void testPotato(
      Class<? extends Collection> implClazz, Class<? extends List> argClazz) throws Throwable {
    try {
      System.out.printf("implClazz=%s, argClazz=%s\n", implClazz.getName(), argClazz.getName());
      final int iterations = 100000;
      final List<Integer> list = (List<Integer>) argClazz.newInstance();
      final Integer one = Integer.valueOf(1);
      final List<Integer> oneElementList = Collections.singletonList(one);
      final Constructor<? extends Collection> constr = implClazz.getConstructor(Collection.class);
      final Thread t =
          new CheckedThread() {
            public void realRun() {
              for (int i = 0; i < iterations; i++) {
                list.add(one);
                list.remove(one);
              }
            }
          };
      t.setDaemon(true);
      t.start();

      for (int i = 0; i < iterations; i++) {
        Collection<?> coll = constr.newInstance(list);
        Object[] elts = coll.toArray();
        check(elts.length == 0 || (elts.length == 1 && elts[0] == one));
      }
    } catch (Throwable t) {
      unexpected(t);
    }
  }
Esempio n. 16
0
  public Integer call() {
    count = 0;
    try {
      File[] files = directory.listFiles();
      ArrayList<Future<Integer>> results = new ArrayList<Future<Integer>>();

      for (File file : files)
        if (file.isDirectory()) {
          MatchCounter counter = new MatchCounter(file, keyword);
          FutureTask<Integer> task = new FutureTask<Integer>(counter);
          results.add(task);
          Thread t = new Thread(task);
          t.start();
        } else {
          if (search(file)) count++;
        }

      for (Future<Integer> result : results)
        try {
          count += result.get();
        } catch (ExecutionException e) {
          e.printStackTrace();
        }
    } catch (InterruptedException e) {
    }
    return count;
  }
 private void initialize(Namespace namespace, long instanceOid) {
   this.namespace = namespace;
   this.instanceOid = instanceOid;
   updater = new Updater();
   Thread updaterThread = new Thread(updater);
   updaterThread.start();
 }
Esempio n. 18
0
  public void run() throws IOException {
    ServerSocket server = new ServerSocket(this.portNumber);
    this.socket = server.accept();
    this.socket.setTcpNoDelay(true);
    server.close();

    DataInputStream in = new DataInputStream(this.socket.getInputStream());
    final DataOutputStream out = new DataOutputStream(this.socket.getOutputStream());
    while (true) {
      final String className = in.readUTF();
      Thread thread =
          new Thread() {
            public void run() {
              try {
                loadAndRun(className);
                out.writeBoolean(true);
                System.err.println(VerifyTests.class.getName());
                System.out.println(VerifyTests.class.getName());
              } catch (Throwable e) {
                e.printStackTrace();
                try {
                  System.err.println(VerifyTests.class.getName());
                  System.out.println(VerifyTests.class.getName());
                  out.writeBoolean(false);
                } catch (IOException e1) {
                  // ignore
                }
              }
            }
          };
      thread.start();
    }
  }
Esempio n. 19
0
 /** Called by ImageJ when the user selects Quit. */
 public void quit() {
   quitMacro = IJ.macroRunning();
   Thread thread = new Thread(this, "Quit");
   thread.setPriority(Thread.NORM_PRIORITY);
   thread.start();
   IJ.wait(10);
 }
Esempio n. 20
0
    protected void openFromPath(final String path) {
      Thread t =
          new Thread(
              new Runnable() {
                public void run() {
                  final ArrayList<Airspace> airspaces = new ArrayList<Airspace>();
                  try {
                    loadAirspacesFromPath(path, airspaces);
                  } finally {
                    SwingUtilities.invokeLater(
                        new Runnable() {
                          public void run() {
                            setAirspaces(airspaces);
                            setEnabled(true);
                            getApp().setCursor(null);
                            getApp().getWwd().redraw();
                          }
                        });
                  }
                }
              });

      this.setEnabled(false);
      getApp().setCursor(new Cursor(Cursor.WAIT_CURSOR));
      t.start();
    }
Esempio n. 21
0
 public void actionPerformed(ActionEvent ae) {
   String action = ae.getActionCommand();
   if (action.equals("refresh")) {
     routerThread = new Thread(this);
     routerThread.start();
   }
 }
 @Override
 public synchronized void start() {
   if (!closed) throw new IllegalStateException("Can't start already running river");
   logger.info("starting Remote River");
   synchronized (riverInstances) {
     addRunningInstance(this);
   }
   refreshSearchIndex(getRiverIndexName());
   try {
     if ((permanentStopDate = readDatetimeValue(null, PERMSTOREPROP_RIVER_STOPPED_PERMANENTLY))
         != null) {
       logger.info(
           "Remote River indexing process not started because stopped permanently, you can restart it over management REST API");
       return;
     }
   } catch (IOException e) {
     // OK, we will start river
   }
   logger.info("starting Remote River indexing process");
   closed = false;
   lastRestartDate = new Date();
   coordinatorInstance =
       new SpaceIndexerCoordinator(
           remoteSystemClient,
           this,
           documentIndexStructureBuilder,
           indexUpdatePeriod,
           maxIndexingThreads,
           indexFullUpdatePeriod,
           indexFullUpdateCronExpression,
           spaceIndexingMode);
   coordinatorThread = acquireIndexingThread("remote_river_coordinator", coordinatorInstance);
   coordinatorThread.start();
 }
Esempio n. 23
0
  /**
   * Constructor declaration
   *
   * @param db
   * @param system
   * @param name
   * @exception SQLException Description of the Exception
   */
  Log(Database db, Session system, String name) throws SQLException {

    dDatabase = db;
    sysSession = system;
    sName = name;
    pProperties = db.getProperties();
    tRunner = new Thread(this);

    // boucherb@users - FIXME:
    // standard VM behaviour is to shut down only after all
    // non-daemon threads exit.  Therefor, tRunner shuld be
    // daemon.  Consider the case of:
    /*
    public void main(String[] args) {
    ...
    try {
    // fails due to bad user/password...must then connect with valid combo
    // again to *really* shutdown database, or explicitly call System.exit(...)
    DriverManager.getConnection("jdbc:hsqldb:filespec,"user","password");
    ...
    } catch (...) {
    }
    ...
    }
    */

    // the VM will not exit, since tRunner is still running and
    // no shutdown is issued to close the database.
    //
    //  - setDaemon(false) may require flush in finalization
    // CB
    // tRunner.setDaemon(false);
    tRunner.start();
  }
Esempio n. 24
0
  public boolean shutdown() throws RemoteException {

    FlightRM flight1 = new FlightRM();
    Thread t = new Thread(flight1);
    t.start();
    return true;
  }
Esempio n. 25
0
  /** begin displaying the message */
  public void begin() {

    g2d.clearAll = false;
    g2d.paintAll = false;

    super.start();
  }
Esempio n. 26
0
  public AnimationFrame() {
    ArrayComponent comp = new ArrayComponent();
    add(comp, BorderLayout.CENTER);

    final Sorter sorter = new Sorter(comp);

    JButton runButton = new JButton("Run");
    runButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent event) {
            sorter.setRun();
          }
        });

    JButton stepButton = new JButton("Step");
    stepButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent event) {
            sorter.setStep();
          }
        });

    JPanel buttons = new JPanel();
    buttons.add(runButton);
    buttons.add(stepButton);
    add(buttons, BorderLayout.NORTH);
    setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

    Thread t = new Thread(sorter);
    t.start();
  }
Esempio n. 27
0
 public void run() {
   if (Thread.currentThread() != this.mt)
     throw (new RuntimeException("MainFrame is being run from an invalid context"));
   Thread ui = new HackThread(p, "Haven UI thread");
   ui.start();
   try {
     try {
       Session sess = null;
       while (true) {
         UI.Runner fun;
         if (sess == null) {
           Bootstrap bill = new Bootstrap(Config.defserv, Config.mainport);
           if ((Config.authuser != null) && (Config.authck != null)) {
             bill.setinitcookie(Config.authuser, Config.authck);
             Config.authck = null;
           }
           fun = bill;
           setTitle(String.format("Amish Paradise %s", version));
         } else {
           fun = new RemoteUI(sess);
           setTitle(String.format("Amish Paradise %s \u2013 %s", version, sess.username));
         }
         sess = fun.run(p.newui(sess));
       }
     } catch (InterruptedException e) {
     }
     savewndstate();
   } finally {
     ui.interrupt();
     dispose();
   }
 }
Esempio n. 28
0
  /**
   * 'handler' can be of any type that implements 'exportedInterface', but only methods declared by
   * the interface (and its superinterfaces) will be invocable.
   */
  public <T> InAppServer(
      String name,
      String portFilename,
      InetAddress inetAddress,
      Class<T> exportedInterface,
      T handler) {
    this.fullName = name + "Server";
    this.exportedInterface = exportedInterface;
    this.handler = handler;

    // In the absence of authentication, we shouldn't risk starting a server as root.
    if (System.getProperty("user.name").equals("root")) {
      Log.warn(
          "InAppServer: refusing to start unauthenticated server \"" + fullName + "\" as root!");
      return;
    }

    try {
      File portFile = FileUtilities.fileFromString(portFilename);
      secretFile = new File(portFile.getPath() + ".secret");
      Thread serverThread = new Thread(new ConnectionAccepter(portFile, inetAddress), fullName);
      // If there are no other threads left, the InApp server shouldn't keep us alive.
      serverThread.setDaemon(true);
      serverThread.start();
    } catch (Throwable th) {
      Log.warn("InAppServer: couldn't start \"" + fullName + "\".", th);
    }
    writeNewSecret();
  }
Esempio n. 29
0
  private void close(Collection<Interpreter> intpToClose) {
    if (intpToClose == null) {
      return;
    }
    List<Thread> closeThreads = new LinkedList<>();

    for (final Interpreter intp : intpToClose) {
      Thread t =
          new Thread() {
            public void run() {
              Scheduler scheduler = intp.getScheduler();
              intp.close();

              if (scheduler != null) {
                SchedulerFactory.singleton().removeScheduler(scheduler.getName());
              }
            }
          };

      t.start();
      closeThreads.add(t);
    }

    for (Thread t : closeThreads) {
      try {
        t.join();
      } catch (InterruptedException e) {
        LOGGER.error("Can't close interpreter", e);
      }
    }
  }
Esempio n. 30
0
  private void setBoardListener() {
    scene.setOnKeyPressed(
        event -> {
          Thread thread =
              new Thread() {
                @Override
                public void run() {
                  if (directionsMapping.keySet().contains(event.getCode().toString())) {
                    if ((inputDirection == 0 && event.getCode().toString().equals("W"))
                        || (inputDirection == 1 && event.getCode().toString().equals("A"))
                        || (inputDirection == 2 && event.getCode().toString().equals("S"))
                        || (inputDirection == 3 && event.getCode().toString().equals("D"))) return;

                    inputDirection = directionsMapping.get(event.getCode().toString());
                  }

                  if (event.getCode().equals(KeyCode.Q)) {
                    if (isPause) isPause = false;
                    else isPause = true;
                  }

                  if (event.getCode().equals(KeyCode.R)) {
                    isReload = true;
                  }
                }
              };
          thread.start();
        });
  }