List of usage examples for java.util.concurrent Executor execute
void execute(Runnable command);
From source file:org.commonjava.indy.filer.ispn.fileio.StorageFileIO.java
@Override public void purge(Executor threadPool, PurgeListener<? super String> listener) { walkFiles((p) -> {/* w ww .j a v a 2s. co m*/ threadPool.execute(() -> { long expiration = -1; try (ObjectInputStream in = new ObjectInputStream( new GZIPInputStream(new FileInputStream(p.toFile())))) { expiration = StorageFileEntry.peekExpiryTime(in); } catch (IOException e) { Logger logger = LoggerFactory.getLogger(getClass()); logger.error("Cannot open file to peek at expiration time: " + p, e); } if (System.currentTimeMillis() > expiration) { p.toFile().delete(); listener.entryPurged(p.relativize(Paths.get(storageRoot)).toString()); } }); }); }
From source file:org.springframework.integration.ip.udp.DatagramPacketSendingHandlerTests.java
@Test @Ignore//from w ww.j av a 2 s. c om public void verifySendMulticast() throws Exception { final int testPort = SocketUtils.findAvailableUdpSocket(); final String multicastAddress = "225.6.7.8"; final String payload = "foo"; final CountDownLatch latch1 = new CountDownLatch(2); final CountDownLatch latch2 = new CountDownLatch(2); Runnable catcher = new Runnable() { public void run() { try { byte[] buffer = new byte[8]; DatagramPacket receivedPacket = new DatagramPacket(buffer, buffer.length); MulticastSocket socket = new MulticastSocket(testPort); InetAddress group = InetAddress.getByName(multicastAddress); socket.joinGroup(group); latch1.countDown(); LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " waiting for packet"); socket.receive(receivedPacket); socket.close(); byte[] src = receivedPacket.getData(); int length = receivedPacket.getLength(); int offset = receivedPacket.getOffset(); byte[] dest = new byte[length]; System.arraycopy(src, offset, dest, 0, length); assertEquals(payload, new String(dest)); LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " received packet"); latch2.countDown(); } catch (Exception e) { noMulticast = true; latch1.countDown(); e.printStackTrace(); } } }; Executor executor = Executors.newFixedThreadPool(2); executor.execute(catcher); executor.execute(catcher); latch1.await(3000, TimeUnit.MILLISECONDS); if (noMulticast) { return; } MulticastSendingMessageHandler handler = new MulticastSendingMessageHandler(multicastAddress, testPort); handler.handleMessage(MessageBuilder.withPayload(payload).build()); assertTrue(latch2.await(3000, TimeUnit.MILLISECONDS)); handler.shutDown(); }
From source file:org.springframework.integration.ip.udp.DatagramPacketSendingHandlerTests.java
@Test @Ignore/*from w w w . j a v a 2 s . co m*/ public void verifySendMulticastWithAcks() throws Exception { final List<Integer> openPorts = SocketUtils.findAvailableUdpSockets(SocketUtils.getRandomSeedPort(), 2); final int testPort = openPorts.get(0); final int ackPort = openPorts.get(1); final String multicastAddress = "225.6.7.8"; final String payload = "foobar"; final CountDownLatch latch1 = new CountDownLatch(2); final CountDownLatch latch2 = new CountDownLatch(2); Runnable catcher = new Runnable() { public void run() { try { byte[] buffer = new byte[1000]; DatagramPacket receivedPacket = new DatagramPacket(buffer, buffer.length); MulticastSocket socket = new MulticastSocket(testPort); InetAddress group = InetAddress.getByName(multicastAddress); socket.joinGroup(group); latch1.countDown(); LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " waiting for packet"); socket.receive(receivedPacket); socket.close(); byte[] src = receivedPacket.getData(); int length = receivedPacket.getLength(); int offset = receivedPacket.getOffset(); byte[] dest = new byte[6]; System.arraycopy(src, offset + length - 6, dest, 0, 6); assertEquals(payload, new String(dest)); LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " received packet"); DatagramPacketMessageMapper mapper = new DatagramPacketMessageMapper(); mapper.setAcknowledge(true); mapper.setLengthCheck(true); Message<byte[]> message = mapper.toMessage(receivedPacket); Object id = message.getHeaders().get(IpHeaders.ACK_ID); byte[] ack = id.toString().getBytes(); DatagramPacket ackPack = new DatagramPacket(ack, ack.length, new InetSocketAddress("localHost", ackPort)); DatagramSocket out = new DatagramSocket(); out.send(ackPack); out.close(); latch2.countDown(); } catch (Exception e) { noMulticast = true; latch1.countDown(); e.printStackTrace(); } } }; Executor executor = Executors.newFixedThreadPool(2); executor.execute(catcher); executor.execute(catcher); latch1.await(3000, TimeUnit.MILLISECONDS); if (noMulticast) { return; } MulticastSendingMessageHandler handler = new MulticastSendingMessageHandler(multicastAddress, testPort, true, true, "localhost", ackPort, 500000); handler.setMinAcksForSuccess(2); handler.handleMessage(MessageBuilder.withPayload(payload).build()); assertTrue(latch2.await(10000, TimeUnit.MILLISECONDS)); handler.shutDown(); }
From source file:org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor.java
/** * Implementation of both the JDK 1.5 Executor interface and the Spring * TaskExecutor interface, delegating to the ThreadPoolExecutor instance. * @see java.util.concurrent.Executor#execute(Runnable) * @see org.springframework.core.task.TaskExecutor#execute(Runnable) *///from w w w. j ava 2 s . c o m public void execute(Runnable task) { Executor executor = getThreadPoolExecutor(); try { executor.execute(task); } catch (RejectedExecutionException ex) { throw new TaskRejectedException("Executor [" + executor + "] did not accept task: " + task, ex); } }
From source file:br.com.valecard.context.event.ChoiceTaskExecutorApplicationEventMulticaster.java
@Override @SuppressWarnings({ "unchecked", "rawtypes" }) public void multicastEvent(final ApplicationEvent event) { Executor executor = getTaskExecutor(); if (event instanceof RepositoryEvent) { executor = new SyncTaskExecutor(); }/*from w w w . j a v a2 s.c om*/ for (final ApplicationListener listener : getApplicationListeners(event)) { if (executor != null) { executor.execute(new Runnable() { @Override public void run() { listener.onApplicationEvent(event); } }); } else { listener.onApplicationEvent(event); } } }
From source file:org.onlab.nio.service.IOLoopMessaging.java
@Override public void registerHandler(String type, Function<byte[], byte[]> handler, Executor executor) { handlers.put(type, message -> executor.execute(() -> { byte[] responsePayload = handler.apply(message.payload()); if (responsePayload != null) { DefaultMessage response = new DefaultMessage(message.id(), localEp, REPLY_MESSAGE_TYPE, responsePayload);// w w w .j a va 2 s .c o m sendAsync(message.sender(), response).whenComplete((result, error) -> { log.debug("Failed to respond", error); }); } })); }
From source file:tayler.TailerTest.java
@Test public void testStopWithNoFileUsingExecutor() throws Exception { final File file = new File(getTestDirectory(), "nosuchfile"); assertFalse("nosuchfile should not exist", file.exists()); TestTailerListener listener = new TestTailerListener(); int delay = 100; int idle = 50; // allow time for thread to work tailer = new Tailer(file, listener, delay, false); Executor exec = new ScheduledThreadPoolExecutor(1); exec.execute(tailer); Thread.sleep(idle);/*www. ja v a 2 s.com*/ tailer.stop(); tailer = null; Thread.sleep(delay + idle); assertNull("Should not generate Exception", listener.exception); assertEquals("Expected init to be called", 1, listener.initialised.get()); assertTrue("fileNotFound should be called", listener.notFound.get() > 0); assertEquals("fileRotated should be not be called", 0, listener.rotated.get()); }
From source file:ch.windmobile.server.socialmodel.mogodb.HeavyLoadTest.java
public void testFullChatCycle() throws Exception { ServiceLocator locator = new MongoDBServiceLocator().connect(null); try {// ww w . j a v a 2s .c o m final int CNT = 50000; final Executor executor = Executors.newFixedThreadPool(10); final ChatService chatService = locator.getService(ChatService.class); final AtomicInteger counter = new AtomicInteger(); final CountDownLatch latch = new CountDownLatch(CNT); for (int i = 0; i < CNT; i++) { executor.execute(new Runnable() { @Override public void run() { chatService.postMessage("TestRoom", "aUser", "Hello, this is my message " + counter.incrementAndGet(), ""); latch.countDown(); } }); } System.out.println("Chat sent, waiting for the end..."); latch.await(2, TimeUnit.MINUTES); Messages ret = chatService.findMessages("TEST", 5); System.out.println("result : " + ret); } finally { locator.disconnect(); } }
From source file:com.turn.ttorrent.common.TorrentCreator.java
/** * Return the concatenation of the SHA-1 hashes of a file's pieces. * * <p>// w ww . ja va 2 s. c o m * Hashes the given file piece by piece using the default Torrent piece * length (see {@link #PIECE_LENGTH}) and returns the concatenation of * these hashes, as a string. * </p> * * <p> * This is used for creating Torrent meta-info structures from a file. * </p> * * @param file The file to hash. */ public /* for testing */ static byte[] hashFiles(Executor executor, List<File> files, long nbytes, int pieceLength) throws InterruptedException, IOException { int npieces = (int) Math.ceil((double) nbytes / pieceLength); byte[] out = new byte[Torrent.PIECE_HASH_SIZE * npieces]; CountDownLatch latch = new CountDownLatch(npieces); ByteBuffer buffer = ByteBuffer.allocate(pieceLength); long start = System.nanoTime(); int piece = 0; for (File file : files) { logger.info("Hashing data from {} ({} pieces)...", new Object[] { file.getName(), (int) Math.ceil((double) file.length() / pieceLength) }); FileInputStream fis = FileUtils.openInputStream(file); FileChannel channel = fis.getChannel(); int step = 10; try { while (channel.read(buffer) > 0) { if (buffer.remaining() == 0) { buffer.flip(); executor.execute(new ChunkHasher(out, piece, latch, buffer)); buffer = ByteBuffer.allocate(pieceLength); piece++; } if (channel.position() / (double) channel.size() * 100f > step) { logger.info(" ... {}% complete", step); step += 10; } } } finally { channel.close(); fis.close(); } } // Hash the last bit, if any if (buffer.position() > 0) { buffer.flip(); executor.execute(new ChunkHasher(out, piece, latch, buffer)); piece++; } // Wait for hashing tasks to complete. latch.await(); long elapsed = System.nanoTime() - start; logger.info("Hashed {} file(s) ({} bytes) in {} pieces ({} expected) in {}ms.", new Object[] { files.size(), nbytes, piece, npieces, String.format("%.1f", elapsed / 1e6) }); return out; }
From source file:edu.umn.msi.tropix.common.io.impl.AsyncStreamCopierImplTest.java
public void mockTest(final boolean close, final boolean exception) { final AsyncStreamCopierImpl copier = new AsyncStreamCopierImpl(); final Executor executor = EasyMock.createMock(Executor.class); final IOUtils ioUtils = EasyMock.createMock(IOUtils.class); final Reference<Runnable> runnableReference = EasyMockUtils.newReference(); executor.execute(EasyMockUtils.record(runnableReference)); copier.setExecutor(executor);/* w ww . j a v a 2s . c o m*/ copier.setIOUtils(ioUtils); EasyMock.replay(executor); final InputStream input = new ByteArrayInputStream("moo".getBytes()); final OutputStream output = new ByteArrayOutputStream(); copier.copy(input, output, close); EasyMock.verify(executor); ioUtils.copy(EasyMock.same(input), EasyMock.same(output)); if (exception) { EasyMock.expectLastCall().andThrow(new NullPointerException()); } else { EasyMock.expectLastCall().andReturn(14); } if (close) { ioUtils.closeQuietly(output); } EasyMock.replay(ioUtils); Exception e = null; try { runnableReference.get().toString(); runnableReference.get().run(); } catch (final Exception ie) { e = ie; } if (exception) { assert e != null; } EasyMock.verify(ioUtils); }