List of usage examples for java.util.concurrent TimeUnit MILLISECONDS
TimeUnit MILLISECONDS
To view the source code for java.util.concurrent TimeUnit MILLISECONDS.
Click Source Link
From source file:org.geoserver.wps.executor.DefaultProcessManager.java
public void setMaxAsynchronousProcesses(int maxAsynchronousProcesses) { if (asynchService == null) { // create a fixed size pool. If we allow a delta between core and max // the pool will create new threads only if the queue is full, but the linked queue never is asynchService = new ThreadPoolExecutor(maxAsynchronousProcesses, maxAsynchronousProcesses, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); } else {/*www . j ava2s.c o m*/ asynchService.setCorePoolSize(maxAsynchronousProcesses); asynchService.setMaximumPoolSize(maxAsynchronousProcesses); } }
From source file:com.brienwheeler.lib.concurrent.ExecutorsTest.java
@Test public void testNewSingleThreadExecutorShutdownClean() throws InterruptedException { NamedThreadFactory threadFactory = new NamedThreadFactory(THREAD_FACTORY_NAME); ExecutorService executor = Executors.newSingleThreadExecutor(threadFactory); Assert.assertFalse(executor.isShutdown()); Assert.assertFalse(executor.isTerminated()); executor.execute(new NullRunnable()); executor.shutdown();//from w ww . ja v a 2s .c om Assert.assertTrue(executor.isShutdown()); executor.awaitTermination(10, TimeUnit.MILLISECONDS); Assert.assertTrue(executor.isTerminated()); }
From source file:com.verigreen.common.command.TEQCommandExecuter.java
public <TCommandParameters extends TEQCommandParameters> void execute( List<CommandPack<TCommandParameters>> commandPacks) throws InterruptedException { List<Callable<Void>> callables = createCallables(commandPacks); List<Future<Void>> futures = ExecutorServiceFactory.getCachedThreadPoolExecutor().invokeAll(callables, _timeoutMillis, TimeUnit.MILLISECONDS); getResults(commandPacks, futures);/*from w w w . ja va2 s . c o m*/ }
From source file:business.services.PasswordService.java
@Transactional public void resetPassword(@NotNull NewPasswordRepresentation body) { NewPasswordRequest npr = newPasswordRequestRepository.findByToken(body.getToken()); if (npr == null) { // The token doesn't exist. log.warn("Token not found."); throw new PasswordChangeFailed(); }//from w ww . ja va 2 s. c o m // Check if the link is not older than <var>passwordLinkExpiryHours</var> hours. log.info("Password link: expiry hours = " + passwordLinkExpiryHours); long linkAge = TimeUnit.MILLISECONDS.toHours(new Date().getTime() - npr.getCreationDate().getTime()); // hours log.info("Password link age in hours: " + linkAge); if (linkAge > passwordLinkExpiryHours) { // The token is expired. log.warn("Token expired."); throw new PasswordChangeFailed(); } if (!PasswordValidator.validate(body.getPassword())) { // The password is invalid! // Validation should never fail since there is client-side validation. log.warn("Invalid password."); throw new PasswordChangeFailed(); } // Update the password of the user and delete the npr User user = npr.getUser(); user.setPassword(passwordEncoder.encode(body.getPassword())); if (!user.isEmailValidated()) { user.setEmailValidated(true); } this.userService.save(user); newPasswordRequestRepository.delete(npr); }
From source file:Main.java
/** * This method returns the number of milliseconds (UTC time) for today's date at midnight in * the local time zone. For example, if you live in California and the day is September 20th, * 2016 and it is 6:30 PM, it will return 1474329600000. Now, if you plug this number into an * Epoch time converter, you may be confused that it tells you this time stamp represents 8:00 * PM on September 19th local time, rather than September 20th. We're concerned with the GMT * date here though, which is correct, stating September 20th, 2016 at midnight. * * As another example, if you are in Hong Kong and the day is September 20th, 2016 and it is * 6:30 PM, this method will return 1474329600000. Again, if you plug this number into an Epoch * time converter, you won't get midnight for your local time zone. Just keep in mind that we * are just looking at the GMT date here. * * This method will ALWAYS return the date at midnight (in GMT time) for the time zone you * are currently in. In other words, the GMT date will always represent your date. * * Since UTC / GMT time are the standard for all time zones in the world, we use it to * normalize our dates that are stored in the database. When we extract values from the * database, we adjust for the current time zone using time zone offsets. * * @return The number of milliseconds (UTC / GMT) for today's date at midnight in the local * time zone// ww w.ja va 2 s .co m */ public static long getNormalizedUtcDateForToday() { /* * This number represents the number of milliseconds that have elapsed since January * 1st, 1970 at midnight in the GMT time zone. */ long utcNowMillis = System.currentTimeMillis(); /* * This TimeZone represents the device's current time zone. It provides us with a means * of acquiring the offset for local time from a UTC time stamp. */ TimeZone currentTimeZone = TimeZone.getDefault(); /* * The getOffset method returns the number of milliseconds to add to UTC time to get the * elapsed time since the epoch for our current time zone. We pass the current UTC time * into this method so it can determine changes to account for daylight savings time. */ long gmtOffsetMillis = currentTimeZone.getOffset(utcNowMillis); /* * UTC time is measured in milliseconds from January 1, 1970 at midnight from the GMT * time zone. Depending on your time zone, the time since January 1, 1970 at midnight (GMT) * will be greater or smaller. This variable represents the number of milliseconds since * January 1, 1970 (GMT) time. */ long timeSinceEpochLocalTimeMillis = utcNowMillis + gmtOffsetMillis; /* This method simply converts milliseconds to days, disregarding any fractional days */ long daysSinceEpochLocal = TimeUnit.MILLISECONDS.toDays(timeSinceEpochLocalTimeMillis); /* * Finally, we convert back to milliseconds. This time stamp represents today's date at * midnight in GMT time. We will need to account for local time zone offsets when * extracting this information from the database. */ long normalizedUtcMidnightMillis = TimeUnit.DAYS.toMillis(daysSinceEpochLocal); return normalizedUtcMidnightMillis; }
From source file:com.cloudbees.hudson.plugins.folder.computed.EventOutputStreamsTest.java
public void test(final boolean aFlush, final boolean bFlush) throws Exception { final File file = work.newFile(); final EventOutputStreams instance = new EventOutputStreams(new EventOutputStreams.OutputFile() { @NonNull//from w ww . ja v a 2 s . c o m @Override public File get() { return file; } }, 250, TimeUnit.MILLISECONDS, 8192, false, Long.MAX_VALUE, 0); Thread t1 = new Thread() { public void run() { OutputStream os = instance.get(); try { PrintWriter pw = new PrintWriter(os, aFlush); for (int i = 0; i < 10000; i += 1) { pw.println(String.format("%1$05dA", i)); } pw.flush(); } catch (Throwable e) { e.printStackTrace(System.err); } finally { IOUtils.closeQuietly(os); } } }; Thread t2 = new Thread() { public void run() { OutputStream os = instance.get(); try { PrintWriter pw = new PrintWriter(os, bFlush); for (int i = 0; i < 10000; i += 1) { pw.println(String.format("%1$05dB", i)); } pw.flush(); } catch (Throwable e) { e.printStackTrace(System.err); } finally { IOUtils.closeQuietly(os); } } }; t1.start(); t2.start(); t1.join(); t2.join(); List<String> as = new ArrayList<String>(); List<String> bs = new ArrayList<String>(); for (String line : FileUtils.readLines(file)) { assertThat("Line does not have both thread output: '" + StringEscapeUtils.escapeJava(line) + "'", line.matches("^\\d+[AB](\\d+[AB])+$"), is(false)); assertThat("Line does not contain a null character: '" + StringEscapeUtils.escapeJava(line) + "'", line.indexOf(0), is(-1)); if (line.endsWith("A")) { as.add(line); } else if (line.endsWith("B")) { bs.add(line); } else { fail("unexpected line: '" + StringEscapeUtils.escapeJava(line) + "'"); } } List<String> sorted = new ArrayList<String>(as); Collections.sort(sorted); assertThat(as, is(sorted)); sorted = new ArrayList<String>(bs); Collections.sort(sorted); assertThat(bs, is(sorted)); }
From source file:org.redisson.spring.cache.RedissonCache.java
@Override public void put(Object key, Object value) { if (mapCache != null) { mapCache.fastPut(key, value, config.getTTL(), TimeUnit.MILLISECONDS, config.getMaxIdleTime(), TimeUnit.MILLISECONDS); } else {//from ww w . j ava 2 s . com map.fastPut(key, value); } }
From source file:unitTests.v1_0.pdf.ConvertUrlToPDFTest.java
@Test public void convertUrlToPdf() { try {/*from w ww. j a v a2 s.c o m*/ Url2PdfJob args = new Url2PdfJob(); args.setPath("http://www.mikenimer.com"); args.setFontEmbed(true); args.setMarginBottom(2); args.setMarginTop(2); args.setMarginLeft(2); args.setMarginRight(2); CFDocumentJob.Permission[] permissions = new CFDocumentJob.Permission[] { CFDocumentJob.Permission.AllowCopy, CFDocumentJob.Permission.AllowPrinting, CFDocumentJob.Permission.AllowScreenReaders }; args.setPermissions(permissions); Future<Map> resultFuture = pdfUrlGateway.convertUrlToPdf(args); Object result = resultFuture.get(defaultTimeout, TimeUnit.MILLISECONDS); Assert.assertTrue(result != null); Assert.assertTrue(((Url2PdfJob) result).getPdfBytes().length > 500000); } catch (Exception ex) { ex.printStackTrace(); Assert.fail(ex.getMessage()); } }
From source file:com.phattn.vnexpressnews.io.OkHttpStack.java
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { OkHttpClient client = mClient.clone(); int timeoutMs = request.getTimeoutMs(); client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS); client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS); client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS); com.squareup.okhttp.Request.Builder okHttpRequestBuilder = new com.squareup.okhttp.Request.Builder(); okHttpRequestBuilder.url(request.getUrl()); Map<String, String> headers = request.getHeaders(); for (final String name : headers.keySet()) { okHttpRequestBuilder.addHeader(name, headers.get(name)); }/*from w w w .j a v a 2 s .c o m*/ for (final String name : additionalHeaders.keySet()) { okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name)); } setConnectionParametersForRequest(okHttpRequestBuilder, request); com.squareup.okhttp.Request okHttpRequest = okHttpRequestBuilder.build(); Call okHttpCall = client.newCall(okHttpRequest); Response okHttpResponse = okHttpCall.execute(); StatusLine responseStatus = new BasicStatusLine(parseProtocol(okHttpResponse.protocol()), okHttpResponse.code(), okHttpResponse.message()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromOkHttpResponse(okHttpResponse)); Headers responseHeaders = okHttpResponse.headers(); for (int i = 0, length = responseHeaders.size(); i < length; i++) { final String name = responseHeaders.name(i); final String value = responseHeaders.value(i); if (name != null) { response.addHeader(new BasicHeader(name, value)); } } return response; }
From source file:de.uni_koeln.spinfo.maalr.sigar.SigarWrapper.java
public static SigarReporter newReporter(int milliSeconds) { SigarReporter reporter = new SigarReporter(getSigarInstance()); executors.scheduleWithFixedDelay(reporter, 0, milliSeconds, TimeUnit.MILLISECONDS); return reporter; }