public static void shutdown() {
    logger_.info("Shutting down ...");
    synchronized (MessagingService.class) {
      /* Stop listening on any socket */
      for (SelectionKey skey : listenSockets_.values()) {
        SelectorManager.getSelectorManager().cancel(skey);
      }
      listenSockets_.clear();

      /* Shutdown the threads in the EventQueue's */
      messageDeserializationExecutor_.shutdownNow();
      messageSerializerExecutor_.shutdownNow();
      messageDeserializerExecutor_.shutdownNow();
      streamExecutor_.shutdownNow();

      /* shut down the cachetables */
      taskCompletionMap_.shutdown();
      callbackMap_.shutdown();

      /* Interrupt the selector manager thread */
      SelectorManager.getSelectorManager().interrupt();

      poolTable_.clear();
      verbHandlers_.clear();
      bShutdown_ = true;
    }
    logger_.debug("Shutdown invocation complete.");
  }
Esempio n. 2
0
  public static void main(String[] args) throws Exception {
    ExecutorService exec = Executors.newCachedThreadPool();
    for (int i = 0; i < 5; i++) exec.execute(new Task());
    exec.execute(new Task2());
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(
        new TimerTask() {
          boolean prod = true;

          public void run() {
            if (prod) {
              System.out.print("\nnotify() ");
              Task.blocker.prod();
              prod = false;
            } else {
              System.out.print("\nnotifyAll() ");
              Task.blocker.prodAll();
              prod = true;
            }
          }
        },
        400,
        400); // Run every .4 second
    TimeUnit.SECONDS.sleep(5); // Run for a while...
    timer.cancel();
    System.out.println("\nTimer canceled");
    TimeUnit.MILLISECONDS.sleep(500);
    System.out.print("Task2.blocker.prodAll() ");
    Task2.blocker.prodAll();
    TimeUnit.MILLISECONDS.sleep(500);
    System.out.println("\nShutting down");
    exec.shutdownNow(); // Interrupt all tasks
  }
Esempio n. 3
0
 public void run() {
   for (DelayedTask pt : sequence) {
     printnb(pt.summary() + " ");
   }
   print();
   print(this + " Calling shutdownNow()");
   exec.shutdownNow();
 }
 public static void main(String[] args) throws Exception {
   ExecutorService exec = Executors.newCachedThreadPool();
   for (int i = 0; i < N_ELEMENTS; i++)
     for (int j = 0; j < N_GENES; j++) GRID[i][j] = new AtomicInteger(rand.nextInt(1000));
   for (int i = 0; i < N_EVOLVERS; i++) exec.execute(new Evolver());
   TimeUnit.SECONDS.sleep(5);
   exec.shutdownNow();
 }
Esempio n. 5
0
 public void shutdown() {
   if (_inMemDs != null) {
     shutdownInternalDB(_inMemDs);
     _inMemDs = null;
   }
   if (_executor != null) {
     _executor.shutdownNow();
     _executor = null;
   }
 }
Esempio n. 6
0
 private void shutdownAndAwaitTermination(int seconds) {
   // disable submission of new tasks
   executorService.shutdown();
   try {
     // wait for existing tasks to terminate
     if (!executorService.awaitTermination(seconds, TimeUnit.SECONDS)) {
       // cancel lingering tasks
       executorService.shutdownNow();
       // wait for lingering tasks to terminate
       if (!executorService.awaitTermination(seconds, TimeUnit.SECONDS)) {
         System.err.println("executorService did not terminate!");
       }
     }
   } catch (InterruptedException ie) {
     // (re-)cancel if current thread also interrupted
     executorService.shutdownNow();
     // preserve interrupt status
     Thread.currentThread().interrupt();
   }
 }
Esempio n. 7
0
 public static void main(String[] args) throws Exception {
   if (args.length > 0) size = new Integer(args[0]);
   if (args.length > 1) delay = new Integer(args[1]);
   ExecutorService exec = Executors.newCachedThreadPool();
   Exchanger<List<Fat>> xc = new Exchanger<List<Fat>>();
   List<Fat> producerList = new CopyOnWriteArrayList<Fat>(),
       consumerList = new CopyOnWriteArrayList<Fat>();
   exec.execute(new ExchangerProducer<Fat>(xc, BasicGenerator.create(Fat.class), producerList));
   exec.execute(new ExchangerConsumer<Fat>(xc, consumerList));
   TimeUnit.SECONDS.sleep(delay);
   exec.shutdownNow();
 }
 public static void main(String[] args) throws Exception {
   ToastQueue dryQueue = new ToastQueue(),
       butteredQueue = new ToastQueue(),
       finishedQueue = new ToastQueue();
   ExecutorService exec = Executors.newCachedThreadPool();
   exec.execute(new Toaster(dryQueue));
   exec.execute(new Butterer(dryQueue, butteredQueue));
   exec.execute(new Jammer(butteredQueue, finishedQueue));
   exec.execute(new Eater(finishedQueue));
   TimeUnit.SECONDS.sleep(5);
   exec.shutdownNow();
 }
 public static void main(String[] args) throws Exception {
   ExecutorService exec = Executors.newCachedThreadPool();
   Restaurant restaurant = new Restaurant(exec, 5, 2);
   exec.execute(restaurant);
   if (args.length > 0) // Optional argument
   TimeUnit.SECONDS.sleep(new Integer(args[0]));
   else {
     print("Press ‘Enter’ to quit");
     System.in.read();
   }
   exec.shutdownNow();
 }
 public static void main(String[] args) throws Exception {
   ExecutorService exec = Executors.newCachedThreadPool();
   // If line is too long, customers will leave:
   CustomerLine customers = new CustomerLine(MAX_LINE_SIZE);
   exec.execute(new CustomerGenerator(customers));
   // Manager will add and remove tellers as necessary:
   exec.execute(new TellerManager(exec, customers, ADJUSTMENT_PERIOD));
   if (args.length > 0) // Optional argument
   TimeUnit.SECONDS.sleep(new Integer(args[0]));
   else {
     System.out.println("Press ‘Enter’ to quit");
     System.in.read();
   }
   exec.shutdownNow();
 }
Esempio n. 11
0
 public static void main(String[] args) throws Exception {
   try {
     lock = new Object();
     if (args.length > 0) {
       NUM = Integer.parseInt(args[0]);
     }
     execs = Executors.newFixedThreadPool(5);
     httpServer = createHttpServer(execs);
     port = httpServer.getAddress().getPort();
     pool = Executors.newFixedThreadPool(10);
     httpServer.start();
     for (int i = 0; i < NUM; i++) {
       pool.execute(new Client());
       if (error) {
         throw new Exception("error in test");
       }
     }
     System.out.println("Main thread waiting");
     pool.shutdown();
     long latest = System.currentTimeMillis() + 200 * 1000;
     while (System.currentTimeMillis() < latest) {
       if (pool.awaitTermination(2000L, TimeUnit.MILLISECONDS)) {
         System.out.println("Main thread done!");
         return;
       }
       if (error) {
         throw new Exception("error in test");
       }
     }
     throw new Exception("error in test: timed out");
   } finally {
     httpServer.stop(0);
     pool.shutdownNow();
     execs.shutdownNow();
   }
 }
Esempio n. 12
0
  static void test() throws Throwable {
    final ExecutorService executor = Executors.newCachedThreadPool();

    final NotificationReceiver notifiee1 = new NotificationReceiver();
    final NotificationReceiver notifiee2 = new NotificationReceiver();

    final Collection<Callable<Object>> tasks = new ArrayList<Callable<Object>>();
    tasks.add(new BlockingTask(notifiee1));
    tasks.add(new BlockingTask(notifiee2));
    tasks.add(new NonBlockingTask());

    // start a thread to invoke the tasks
    Thread thread =
        new Thread() {
          public void run() {
            try {
              executor.invokeAll(tasks);
            } catch (RejectedExecutionException t) {
              /* OK */
            } catch (Throwable t) {
              unexpected(t);
            }
          }
        };
    thread.start();

    // Wait until tasks begin execution
    notifiee1.waitForNotification();
    notifiee2.waitForNotification();

    // Now try to shutdown the executor service while tasks
    // are blocked.  This should cause the tasks to be
    // interrupted.
    executor.shutdownNow();
    if (!executor.awaitTermination(5, TimeUnit.SECONDS)) throw new Error("Executor stuck");

    // Wait for the invocation thread to complete.
    thread.join(1000);
    if (thread.isAlive()) {
      thread.interrupt();
      thread.join(1000);
      throw new Error("invokeAll stuck");
    }
  }
 public void testMustNotBeAbleToShutdownGlobalPool() {
   ExecutorService service = AppExecutorUtil.getAppExecutorService();
   try {
     service.shutdown();
     fail();
   } catch (Exception ignored) {
   }
   try {
     service.shutdownNow();
     fail();
   } catch (Exception ignored) {
   }
   try {
     ((ThreadPoolExecutor) service).setThreadFactory(Thread::new);
     fail();
   } catch (Exception ignored) {
   }
   try {
     ((ThreadPoolExecutor) service).setCorePoolSize(0);
     fail();
   } catch (Exception ignored) {
   }
 }
Esempio n. 14
0
 /** Shutdown-related method behaviour when the cluster is running */
 @Test
 public void testShutdownBehaviour() throws Exception {
   ExecutorService executor = createSingleNodeExecutorService("testShutdownBehaviour");
   // Fresh instance, is not shutting down
   assertFalse(executor.isShutdown());
   assertFalse(executor.isTerminated());
   executor.shutdown();
   assertTrue(executor.isShutdown());
   assertTrue(executor.isTerminated());
   // shutdownNow() should return an empty list and be ignored
   List<Runnable> pending = executor.shutdownNow();
   assertTrue(pending.isEmpty());
   assertTrue(executor.isShutdown());
   assertTrue(executor.isTerminated());
   // awaitTermination() should return immediately false
   try {
     boolean terminated = executor.awaitTermination(60L, TimeUnit.SECONDS);
     assertFalse(terminated);
   } catch (InterruptedException ie) {
     fail("InterruptedException");
   }
   assertTrue(executor.isShutdown());
   assertTrue(executor.isTerminated());
 }
  @SuppressWarnings({"unchecked"})
  public final void execute(final Callback callback)
      throws MojoExecutionException, MojoFailureException {
    if (!skip) {
      if (header == null) {
        warn("No header file specified to check for license");
        return;
      }
      if (!strictCheck) {
        warn(
            "Property 'strictCheck' is not enabled. Please consider adding <strictCheck>true</strictCheck> in your pom.xml file.");
        warn("See http://mycila.github.io/license-maven-plugin for more information.");
      }

      finder = new ResourceFinder(basedir);
      try {
        finder.setCompileClassPath(project.getCompileClasspathElements());
      } catch (DependencyResolutionRequiredException e) {
        throw new MojoExecutionException(e.getMessage(), e);
      }
      finder.setPluginClassPath(getClass().getClassLoader());

      final Header h = new Header(finder.findResource(this.header), encoding, headerSections);
      debug("Header %s:\n%s", h.getLocation(), h);

      if (this.validHeaders == null) {
        this.validHeaders = new String[0];
      }
      final List<Header> validHeaders = new ArrayList<Header>(this.validHeaders.length);
      for (String validHeader : this.validHeaders) {
        validHeaders.add(new Header(finder.findResource(validHeader), encoding, headerSections));
      }

      final List<PropertiesProvider> propertiesProviders = new LinkedList<PropertiesProvider>();
      for (PropertiesProvider provider :
          ServiceLoader.load(
              PropertiesProvider.class, Thread.currentThread().getContextClassLoader())) {
        propertiesProviders.add(provider);
      }
      final DocumentPropertiesLoader propertiesLoader =
          new DocumentPropertiesLoader() {
            @Override
            public Properties load(Document document) {
              Properties props = new Properties();

              for (Map.Entry<String, String> entry : mergeProperties(document).entrySet()) {
                if (entry.getValue() != null) {
                  props.setProperty(entry.getKey(), entry.getValue());
                } else {
                  props.remove(entry.getKey());
                }
              }
              for (PropertiesProvider provider : propertiesProviders) {
                try {
                  final Map<String, String> providerProperties =
                      provider.getAdditionalProperties(AbstractLicenseMojo.this, props, document);
                  if (getLog().isDebugEnabled()) {
                    getLog()
                        .debug(
                            "provider: "
                                + provider.getClass()
                                + " brought new properties\n"
                                + providerProperties);
                  }
                  for (Map.Entry<String, String> entry : providerProperties.entrySet()) {
                    if (entry.getValue() != null) {
                      props.setProperty(entry.getKey(), entry.getValue());
                    } else {
                      props.remove(entry.getKey());
                    }
                  }
                } catch (Exception e) {
                  getLog().warn("failure occured while calling " + provider.getClass(), e);
                }
              }
              return props;
            }
          };

      final DocumentFactory documentFactory =
          new DocumentFactory(
              basedir,
              buildMapping(),
              buildHeaderDefinitions(),
              encoding,
              keywords,
              propertiesLoader);

      int nThreads = (int) (Runtime.getRuntime().availableProcessors() * concurrencyFactor);
      ExecutorService executorService = Executors.newFixedThreadPool(nThreads);
      CompletionService completionService = new ExecutorCompletionService(executorService);
      int count = 0;
      debug("Number of execution threads: %s", nThreads);

      try {
        for (final String file : listSelectedFiles()) {
          completionService.submit(
              new Runnable() {
                @Override
                public void run() {
                  Document document = documentFactory.createDocuments(file);
                  debug(
                      "Selected file: %s [header style: %s]",
                      document.getFilePath(), document.getHeaderDefinition());
                  if (document.isNotSupported()) {
                    callback.onUnknownFile(document, h);
                  } else if (document.is(h)) {
                    debug("Skipping header file: %s", document.getFilePath());
                  } else if (document.hasHeader(h, strictCheck)) {
                    callback.onExistingHeader(document, h);
                  } else {
                    boolean headerFound = false;
                    for (Header validHeader : validHeaders) {
                      if (headerFound = document.hasHeader(validHeader, strictCheck)) {
                        callback.onExistingHeader(document, h);
                        break;
                      }
                    }
                    if (!headerFound) {
                      callback.onHeaderNotFound(document, h);
                    }
                  }
                }
              },
              null);
          count++;
        }

        while (count-- > 0) {
          try {
            completionService.take().get();
          } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
          } catch (ExecutionException e) {
            Throwable cause = e.getCause();
            if (cause instanceof Error) {
              throw (Error) cause;
            }
            if (cause instanceof MojoExecutionException) {
              throw (MojoExecutionException) cause;
            }
            if (cause instanceof MojoFailureException) {
              throw (MojoFailureException) cause;
            }
            if (cause instanceof RuntimeException) {
              throw (RuntimeException) cause;
            }
            throw new RuntimeException(cause.getMessage(), cause);
          }
        }

      } finally {
        executorService.shutdownNow();
      }
    }
  }
Esempio n. 16
0
 public List<Runnable> shutdownNow() {
   return e.shutdownNow();
 }