当前位置: 首页>>代码示例>>Java>>正文


Java ThreadUtil类代码示例

本文整理汇总了Java中com.codeforces.commons.process.ThreadUtil的典型用法代码示例。如果您正苦于以下问题:Java ThreadUtil类的具体用法?Java ThreadUtil怎么用?Java ThreadUtil使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


ThreadUtil类属于com.codeforces.commons.process包,在下文中一共展示了ThreadUtil类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: contextInitialized

import com.codeforces.commons.process.ThreadUtil; //导入依赖的package包/类
@Override
public void contextInitialized(ServletContextEvent sce) {
    running.set(true);

    new Thread(new Runnable() {
        @Override
        public void run() {
            while (running.get()) {
                ThreadUtil.sleep(TimeUnit.SECONDS.toMillis(30));

                final String updatePackagesUrl = UPDATE_PACKAGES_URL.get();
                if (StringUtils.isNotBlank(updatePackagesUrl)) {
                    HttpRequest.create(updatePackagesUrl).setMethod(HttpMethod.POST).executeAndReturnResponse();
                }
            }
        }
    }).start();
}
 
开发者ID:MikeMirzayanov,项目名称:pbox,代码行数:19,代码来源:ApplicationListener.java

示例2: findNow

import com.codeforces.commons.process.ThreadUtil; //导入依赖的package包/类
/**
 * @return current date rounded down to seconds
 */
@SuppressWarnings({"AssignmentToStaticFieldFromInstanceMethod", "RefusedBequest"})
@Override
public Date findNow() {
    Date pastDate = new GregorianCalendar(1998, 1, 1).getTime();
    Date result;
    int iterationCount = 0;

    while (true) {
        result = internalFindNow();
        if (result.compareTo(pastDate) > 0) {
            break;
        }

        /* We hope it is impossible case. */
        logger.error("Unable to get current time via internalFindNow(), found " + result + '.');
        iterationCount++;
        if (iterationCount > 2) {
            long sleepTimeMillis = iterationCount * TimeUtil.MILLIS_PER_SECOND;
            logger.error("Sleeping for " + sleepTimeMillis + " ms because of internalFindNow() returns " + result + '.');
            ThreadUtil.sleep(sleepTimeMillis);
        }
    }

    return result;
}
 
开发者ID:MikeMirzayanov,项目名称:pbox,代码行数:29,代码来源:ApplicationDaoImpl.java

示例3: extractFromXml

import com.codeforces.commons.process.ThreadUtil; //导入依赖的package包/类
/**
 * Parses XML string and extracts value.
 *
 * @param xmlFile XML to be scanned.
 * @param xPath   XPath expression.
 * @param clazz   {@link Boolean}, {@link String}, {@link Integer}, {@link Double},
 *                {@link NodeList} and {@link Node} classes are supported now.
 * @param <T>     Return type.
 * @return Return value.
 * @throws IOException In case of I/O error.
 */
public static <T> T extractFromXml(@Nonnull File xmlFile, String xPath, Class<T> clazz)
        throws IOException {
    return Objects.requireNonNull(FileUtil.executeIoOperation(new ThreadUtil.Operation<T>() {
        @Nonnull
        @Override
        public T run() throws IOException {
            try {
                return internalExtractFromXml(new FileInputStream(xmlFile), xPath, clazz);
            } catch (FileNotFoundException e) {
                throw new IOException(String.format(
                        "Can't find file '%s' while evaluating XPath '%s'.", xmlFile.getCanonicalPath(), xPath
                ), e);
            }
        }
    }));
}
 
开发者ID:Codeforces,项目名称:codeforces-commons,代码行数:28,代码来源:XmlUtil.java

示例4: writeXml

import com.codeforces.commons.process.ThreadUtil; //导入依赖的package包/类
/**
 * Writes XML document into file.
 *
 * @param xmlFile  File to write.
 * @param document XML document.
 * @throws IOException In case of I/O error.
 */
public static void writeXml(@Nonnull File xmlFile, @Nonnull Document document) throws IOException {
    FileUtil.executeIoOperation(new ThreadUtil.Operation<Void>() {
        @Nullable
        @Override
        public Void run() throws IOException {
            try {
                internalWriteXml(new FileOutputStream(xmlFile), document);
            } catch (FileNotFoundException e) {
                throw new IOException(
                        "Can't find file '" + xmlFile.getName() + "' while writing XML document.", e
                );
            }
            return null;
        }
    });
}
 
开发者ID:Codeforces,项目名称:codeforces-commons,代码行数:24,代码来源:XmlUtil.java

示例5: ensureXmlElementExists

import com.codeforces.commons.process.ThreadUtil; //导入依赖的package包/类
/**
 * Ensures that XML-element with {@code newAttributes} does exist and creates it if not.
 * <p>&nbsp;</p>
 * Method uses {@code filterAttributes} to uniquely identify an XML-element.
 * If such element does exist, all its attributes will be overridden with values of {@code newAttributes},
 * else a new element will be created.
 *
 * @param xmlInputStream     Stream to read.
 * @param xmlOutputStream    Stream to write.
 * @param parentElementXPath XPath to find element that should contain specified element.
 * @param elementName        Name of the element to create.
 * @param filterAttributes   Collection of attributes which allows to uniquely identify an XML-element.
 * @param newAttributes      Collection of attributes which an XML-element should have
 *                           or {@code null} if {@code filterAttributes} should be considered
 *                           also as {@code newAttributes}.
 * @param obsoleteAttributes Collection of attribute names which should be removed from the element
 *                           or {@code null} if no such action is required.
 * @throws IOException In case of I/O error.
 */
public static void ensureXmlElementExists(
        @Nonnull InputStream xmlInputStream, @Nonnull OutputStream xmlOutputStream,
        @Nonnull String parentElementXPath, @Nonnull String elementName,
        @Nonnull Map<String, String> filterAttributes, @Nullable Map<String, String> newAttributes,
        @Nullable Set<String> obsoleteAttributes) throws IOException {
    FileUtil.executeIoOperation(new ThreadUtil.Operation<Void>() {
        @Nullable
        @Override
        public Void run() throws IOException {
            internalEnsureXmlElementExists(
                    true,
                    xmlInputStream, xmlOutputStream,
                    parentElementXPath, elementName,
                    filterAttributes, newAttributes, obsoleteAttributes
            );
            return null;
        }
    }, 1);
}
 
开发者ID:Codeforces,项目名称:codeforces-commons,代码行数:39,代码来源:XmlUtil.java

示例6: internalExecute

import com.codeforces.commons.process.ThreadUtil; //导入依赖的package包/类
@Nonnull
private HttpResponse internalExecute(boolean readBytes) {
    String internalUrl = appendGetParametersToUrl(this.url);

    if (method == HttpMethod.GET && hasBinaryEntity()) {
        String message = "Can't write binary entity to '" + internalUrl + "' with GET method.";
        logger.warn(message);
        return new HttpResponse(-1, null, null, new IOException(message));
    }

    long startTimeMillis = System.currentTimeMillis();

    for (int attemptIndex = 1; attemptIndex < maxRetryCount; ++attemptIndex) {
        HttpResponse response = internalGetHttpResponse(readBytes, internalUrl, startTimeMillis);
        if (responseChecker.check(response)) {
            return response;
        } else {
            ThreadUtil.sleep(retryStrategy.getDelayTimeMillis(attemptIndex));
        }
    }

    return internalGetHttpResponse(readBytes, internalUrl, startTimeMillis);
}
 
开发者ID:Codeforces,项目名称:codeforces-commons,代码行数:24,代码来源:HttpRequest.java

示例7: testOverridingOfValuesWithLifetime

import com.codeforces.commons.process.ThreadUtil; //导入依赖的package包/类
public static void testOverridingOfValuesWithLifetime(
        Class<?> cacheTestClass, Cache<String, byte[]> cache, int valueLength) {
    determineOperationTime(cacheTestClass.getSimpleName() + ".testOverridingOfValuesWithLifetime", () -> {
        byte[] temporaryBytes = RandomUtil.getRandomBytes(valueLength);
        byte[] finalBytes = RandomUtil.getRandomBytes(valueLength);

        cache.put("S", "K", temporaryBytes, 1000L);
        Assert.assertTrue(
                "Restored value (with lifetime) does not equal to original value.",
                Arrays.equals(temporaryBytes, cache.get("S", "K"))
        );

        cache.put("S", "K", finalBytes, 1000L);
        ThreadUtil.sleep(500L);
        Assert.assertNotNull("Value is 'null' after previous value lifetime expiration.", cache.get("S", "K"));
        Assert.assertEquals("Restored value does not equal to original value.", finalBytes, cache.get("S", "K"));

        ThreadUtil.sleep(1000L);
        Assert.assertNull("Value is not 'null' after lifetime expiration.", cache.get("S", "K"));
    });
}
 
开发者ID:Codeforces,项目名称:codeforces-commons,代码行数:22,代码来源:CacheTestUtil.java

示例8: updateXml

import com.codeforces.commons.process.ThreadUtil; //导入依赖的package包/类
/**
 * Changes the value describing by XPath to specific value and updates file.
 *
 * @param xmlFile Which will read first and updated later.
 * @param xPath   XPath to find specific Node.
 * @param value   Value to be set for found node.
 * @throws IOException In case of I/O error.
 */
public static void updateXml(@Nonnull File xmlFile, String xPath, String value) throws IOException {
    FileUtil.executeIoOperation(new ThreadUtil.Operation<Void>() {
        @Nullable
        @Override
        public Void run() throws IOException {
            try {
                byte[] inputBytes = FileUtil.getBytes(xmlFile);
                ByteArrayInputStream xmlInputStream = new ByteArrayInputStream(inputBytes);
                ByteArrayOutputStream xmlOutputStream = new ByteArrayOutputStream();

                internalUpdateXml(xmlInputStream, xmlOutputStream, xPath, value);

                byte[] outputBytes = xmlOutputStream.toByteArray();
                if (!Arrays.equals(inputBytes, outputBytes)) {
                    FileUtil.writeFile(xmlFile, outputBytes);
                }
            } catch (IOException e) {
                throw new IOException(String.format(
                        "Can't find, read or update file '%s' while evaluating XPath '%s'.",
                        xmlFile.getName(), xPath
                ), e);
            }
            return null;
        }
    });
}
 
开发者ID:Codeforces,项目名称:codeforces-commons,代码行数:35,代码来源:XmlUtil.java

示例9: updateText

import com.codeforces.commons.process.ThreadUtil; //导入依赖的package包/类
/**
 * Changes the inner text of an XML-element described by XPath to specific value and updates file.
 *
 * @param xmlFile Which will read first and updated later.
 * @param xPath   XPath to find specific {@code {@link Element }}.
 * @param value   New text value.
 * @throws IOException In case of I/O error.
 */
public static void updateText(@Nonnull File xmlFile, String xPath, @Nullable String value)
        throws IOException {
    FileUtil.executeIoOperation(new ThreadUtil.Operation<Void>() {
        @Nullable
        @Override
        public Void run() throws IOException {
            try {
                byte[] inputBytes = FileUtil.getBytes(xmlFile);
                ByteArrayInputStream xmlInputStream = new ByteArrayInputStream(inputBytes);
                ByteArrayOutputStream xmlOutputStream = new ByteArrayOutputStream();

                internalUpdateText(xmlInputStream, xmlOutputStream, xPath, value);

                byte[] outputBytes = xmlOutputStream.toByteArray();
                if (!Arrays.equals(inputBytes, outputBytes)) {
                    FileUtil.writeFile(xmlFile, outputBytes);
                }
            } catch (IOException e) {
                throw new IOException(String.format(
                        "Can't find, read or update file '%s' while evaluating XPath '%s'.",
                        xmlFile.getName(), xPath
                ), e);
            }
            return null;
        }
    });
}
 
开发者ID:Codeforces,项目名称:codeforces-commons,代码行数:36,代码来源:XmlUtil.java

示例10: setRetryPolicy

import com.codeforces.commons.process.ThreadUtil; //导入依赖的package包/类
public HttpRequest setRetryPolicy(int maxRetryCount, @Nonnull HttpResponseChecker responseChecker,
                                  @Nonnull ThreadUtil.ExecutionStrategy retryStrategy) {
    Preconditions.checkArgument(maxRetryCount > 0, "Argument 'maxRetryCount' is zero or negative.");
    Objects.requireNonNull(responseChecker, "Argument 'responseChecker' is null.");
    Objects.requireNonNull(retryStrategy, "Argument 'retryStrategy' is null.");
    this.maxRetryCount = maxRetryCount;
    this.responseChecker = responseChecker;
    this.retryStrategy = retryStrategy;
    return this;
}
 
开发者ID:Codeforces,项目名称:codeforces-commons,代码行数:11,代码来源:HttpRequest.java

示例11: getFirstBytes

import com.codeforces.commons.process.ThreadUtil; //导入依赖的package包/类
/**
 * Returns 511 first bytes of the file. Returns smaller number of bytes it it contains less.
 *
 * @param file File to be read.
 * @return File content as a byte array.
 * @throws IOException           if can't read file.
 * @throws FileNotFoundException if can't find file.
 */
@Nonnull
public static FirstBytes getFirstBytes(File file) throws IOException {
    return Objects.requireNonNull(executeIoOperation(new ThreadUtil.Operation<FirstBytes>() {
        @Nonnull
        @Override
        public FirstBytes run() throws IOException {
            return UnsafeFileUtil.getFirstBytes(file);
        }
    }));
}
 
开发者ID:Codeforces,项目名称:codeforces-commons,代码行数:19,代码来源:FileUtil.java

示例12: executeConcurrentStoringOfValues

import com.codeforces.commons.process.ThreadUtil; //导入依赖的package包/类
private static void executeConcurrentStoringOfValues(
        Cache<String, byte[]> cache, CachePath[] cachePaths,
        AtomicReference<AssertionError> assertionError, AtomicReference<Throwable> unexpectedThrowable,
        int totalKeyCount, int valueLength, int threadCount) {
    ExecutorService executorService = Executors.newFixedThreadPool(threadCount, ThreadUtil.getCustomPoolThreadFactory(thread -> thread.setUncaughtExceptionHandler((t, e) -> unexpectedThrowable.set(e))));

    AtomicInteger pathIndexCounter = new AtomicInteger();

    for (int threadIndex = 0; threadIndex < threadCount; ++threadIndex) {
        executorService.execute(() -> {
            int pathIndex;

            while (assertionError.get() == null
                    && (pathIndex = pathIndexCounter.getAndIncrement()) < totalKeyCount) {
                try {
                    checkStoringOneValue(cache, cachePaths[pathIndex], valueLength);
                } catch (AssertionError error) {
                    assertionError.set(error);
                }
            }
        });
    }

    executorService.shutdown();
    try {
        executorService.awaitTermination(1L, TimeUnit.HOURS);
    } catch (InterruptedException ignored) {
        // No operations.
    }

    if (assertionError.get() != null) {
        throw assertionError.get();
    }
}
 
开发者ID:Codeforces,项目名称:codeforces-commons,代码行数:35,代码来源:CacheTestUtil.java

示例13: checkStoringOneValueWithLifetime

import com.codeforces.commons.process.ThreadUtil; //导入依赖的package包/类
public static void checkStoringOneValueWithLifetime(
        Cache<String, byte[]> cache, CachePath cachePath, int valueLength,
        long valueLifetimeMillis, long valueCheckIntervalMillis) {
    String section = cachePath.getSection();
    String key = cachePath.getKey();

    byte[] value = RandomUtil.getRandomBytes(valueLength);

    long cachePutTime = System.currentTimeMillis();
    cache.put(section, key, value, valueLifetimeMillis);
    Assert.assertTrue(
            "Restored value (with lifetime) does not equal to original value.",
            Arrays.equals(value, cache.get(section, key))
    );

    ThreadUtil.sleep(valueLifetimeMillis - valueCheckIntervalMillis);
    byte[] restoredValue = cache.get(section, key);
    Assert.assertTrue(String.format(
            "Restored value (with lifetime) does not equal to original value after sleeping some time (%s) " +
                    "(restored=%s, expected=%s, section=%s, key=%s, valueLifetime=%s, valueCheckInterval=%s).",
            TimeUtil.formatInterval(System.currentTimeMillis() - cachePutTime),
            toShortString(restoredValue), toShortString(value), section, key,
            TimeUtil.formatInterval(valueLifetimeMillis), TimeUtil.formatInterval(valueCheckIntervalMillis)
    ), Arrays.equals(value, restoredValue));

    ThreadUtil.sleep(2L * valueCheckIntervalMillis);
    Assert.assertNull(
            "Restored value (with lifetime) does not equal to 'null' after lifetime expiration.",
            cache.get(section, key)
    );

    cache.put(section, key, value, valueLifetimeMillis);
    Assert.assertTrue(
            "Restored value (with lifetime) does not equal to original value.",
            Arrays.equals(value, cache.get(section, key))
    );

    cache.remove(section, key);
    Assert.assertNull("Value (with lifetime) is not 'null' after removal.", cache.get(section, key));
}
 
开发者ID:Codeforces,项目名称:codeforces-commons,代码行数:41,代码来源:CacheTestUtil.java

示例14: serve

import com.codeforces.commons.process.ThreadUtil; //导入依赖的package包/类
@SuppressWarnings({"RefusedBequest", "OverlyLongMethod"})
@Override
public Response serve(IHTTPSession session) {
    Map<String, String> files = new HashMap<>();

    @Nullable Response response = parseRequest(session, files);
    if (response != null) {
        return response;
    }

    Map<String, String> parameterValueByName = new HashMap<>(session.getParms());

    response = validatePostDataAndUpdateParameters(session, files, parameterValueByName);
    if (response != null) {
        return response;
    }

    String delayString = parameterValueByName.get("delay");
    if (delayString != null) {
        ThreadUtil.sleep(NumberUtil.toInt(delayString));
    }

    String sizeString = parameterValueByName.get("size");
    int size = sizeString == null ? DEFAULT_RESPONSE_SIZE : NumberUtil.toInt(sizeString);

    String randomPrefixPart = getRandomString(TRUE_RANDOM_PART_LENGTH);
    String randomPostfixPart = getRandomString(TRUE_RANDOM_PART_LENGTH);

    String responseBody;
    if (size == DEFAULT_RESPONSE_SIZE) {
        responseBody = randomPrefixPart + randomString1024 + randomPostfixPart;
    } else if (size == LARGE_RESPONSE_SIZE) {
        responseBody = randomPrefixPart + randomString100000 + randomPostfixPart;
    } else {
        throw new IllegalArgumentException(String.format("Unsupported size %d.", size));
    }

    return new Response(Response.Status.OK, MimeUtil.Type.TEXT_PLAIN, responseBody);
}
 
开发者ID:Codeforces,项目名称:codeforces-commons,代码行数:40,代码来源:HttpUtilTest.java

示例15: World

import com.codeforces.commons.process.ThreadUtil; //导入依赖的package包/类
public World(int iterationCountPerStep, int stepCountPerTimeUnit, @Nonnegative double epsilon,
             @Nonnull BodyList bodyList, @Nullable MomentumTransferFactorProvider momentumTransferFactorProvider,
             boolean multithreaded) {
    if (iterationCountPerStep < 1) {
        throw new IllegalArgumentException("Argument 'iterationCountPerStep' is zero or negative.");
    }

    if (stepCountPerTimeUnit < 1) {
        throw new IllegalArgumentException("Argument 'stepCountPerTimeUnit' is zero or negative.");
    }

    if (Double.isNaN(epsilon) || Double.isInfinite(epsilon) || epsilon < 1.0E-100D || epsilon > 1.0D) {
        throw new IllegalArgumentException("Argument 'epsilon' should be between 1.0E-100 and 1.0.");
    }

    if (bodyList == null) {
        throw new IllegalArgumentException("Argument 'bodyList' is null.");
    }

    this.stepCountPerTimeUnit = stepCountPerTimeUnit;
    this.iterationCountPerStep = iterationCountPerStep;
    this.updateFactor = 1.0D / (stepCountPerTimeUnit * iterationCountPerStep);
    this.epsilon = epsilon;
    this.squaredEpsilon = epsilon * epsilon;
    this.bodyList = bodyList;
    this.momentumTransferFactorProvider = momentumTransferFactorProvider;

    this.parallelTaskExecutor = multithreaded ? new ThreadPoolExecutor(
            0, PARALLEL_THREAD_COUNT - 1, 5L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(),
            new ThreadFactory() {
                private final AtomicInteger threadIndex = new AtomicInteger();

                @Override
                public Thread newThread(@Nonnull Runnable runnable) {
                    return ThreadUtil.newThread(
                            "notreal2d.World#ParallelExecutionThread-" + threadIndex.incrementAndGet(), runnable,
                            (t, e) -> logger.error("Can't complete parallel task in thread '" + t + "'.", e),
                            true
                    );
                }
            }
    ) : null;

    registerCollider(new ArcAndArcCollider(epsilon));
    registerCollider(new ArcAndCircleCollider(epsilon));
    registerCollider(new CircleAndCircleCollider(epsilon));
    registerCollider(new LineAndArcCollider(epsilon));
    registerCollider(new LineAndCircleCollider(epsilon));
    registerCollider(new LineAndLineCollider(epsilon));
    registerCollider(new LineAndRectangleCollider(epsilon));
    registerCollider(new RectangleAndArcCollider(epsilon));
    registerCollider(new RectangleAndCircleCollider(epsilon));
    registerCollider(new RectangleAndRectangleCollider(epsilon));
}
 
开发者ID:Russian-AI-Cup,项目名称:notreal2d,代码行数:55,代码来源:World.java


注:本文中的com.codeforces.commons.process.ThreadUtil类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。