请告诉我有什么区别信号量用1和0初始化.如下:
public static Semaphore semOne = new Semaphore(1);
Run Code Online (Sandbox Code Playgroud)
和
public static Semaphore semZero = new Semaphore(0);
Run Code Online (Sandbox Code Playgroud) 一个看似简单的问题:我有一个java.util.concurrent.Semaphore,我希望获得许可证使用acquire().
如果线程被中断,acquire()则指定该方法抛出InterruptedException:
如果当前线程:
- 在进入此方法时设置其中断状态; 要么
- 在等待许可证时被打断,
然后抛出InterruptedException并清除当前线程的中断状态.
但是,使用可能抛出的方法的通常模式InterruptedException是在循环中调用它们,因为线程可能受到虚假唤醒的影响,这些唤醒看起来与被中断相同.例如,文档Object.wait(long)说:
线程也可以在没有被通知,中断或超时的情况下唤醒,即所谓的虚假唤醒.虽然这在实践中很少发生,但应用程序必须通过测试应该导致线程被唤醒的条件来防范它,并且如果条件不满足则继续等待.换句话说,等待应始终在循环中进行.
所以问题是,是否Semaphore.acquire()受到同样的虚假唤醒?合乎逻辑的答案是"不",但我找不到任何证据,实际上证据似乎指向了另一个方向.
查看源代码Semaphore,它似乎将实际的获取委托给a AbstractQueuedSynchronizer,根据其来源代表LockSupport.park().
明确提到虚假唤醒的文档LockSupport.park(),但实现AbstractQueuedSynchronizer.doAcquireInterruptably()似乎只是检查Thread.interrupted()然后抛出InterruptedException.
所以,除非我遗漏了某些东西(这是非常可能的),否则看起来可能Semaphore.acquire() 会抛出InterruptedException虚假的东西?
那是对的吗?更重要的是,我能做些什么吗?我可以使用Semaphore.acquireUninterruptably(),但我不想要一个不间断的等待,只是一个不会被虚假中断的.还有其他选择吗?
我正在处理一些第三方库代码,涉及创建昂贵的对象并将其缓存在Map.现有的实现类似于
lock.lock()
try {
Foo result = cache.get(key);
if (result == null) {
result = createFooExpensively(key);
cache.put(key, result);
}
return result;
} finally {
lock.unlock();
}
Run Code Online (Sandbox Code Playgroud)
显然,当Foos不同的keys可以独立创建时,这不是最好的设计.
我目前的黑客是使用以下Map方法Futures:
lock.lock();
Future<Foo> future;
try {
future = allFutures.get(key);
if (future == null) {
future = executorService.submit(new Callable<Foo>() {
public Foo call() {
return createFooExpensively(key);
}
});
allFutures.put(key, future);
}
} finally {
lock.unlock();
}
try {
return future.get();
} catch (InterruptedException e) …Run Code Online (Sandbox Code Playgroud) Lambda Expressions 的Java教程如下:
本节讨论Project Lambda中包含的功能,旨在通过向Java语言添加闭包和相关功能来支持多核环境中的编程.
我的问题是,根据多核系统和并发/并行编程,Lambda Expressions有哪些具体优势?
使用remove()方法好吗?我读过一篇文章,说明同步还没有添加到remove方法中.如何从ConcurrentHashMap中正确删除特定项?
示例代码:
ConcurrentHashMap<String,Integer> storage = new ConcurrentHashMap<String,Integer>();
storage.put("First", 1);
storage.put("Second", 2);
storage.put("Third",3);
//Is this the proper way of removing a specific item from a tread-safe collection?
storage.remove("First");
for (Entry<String, Integer> entry : storage.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
// ...
System.out.println(key + " " + value);
}
Run Code Online (Sandbox Code Playgroud) 我试图将Quartz Sequential执行更改为并行执行.
它工作正常,性能明智,看起来不错,但Spawned(已创建)线程不会被破坏.
它仍处于Runnable国家; 为什么以及如何解决这个问题?请指导我.
代码在这里:
@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
logger.error("Result Processing executed");
List<Object[]> lstOfExams = examService.getExamEntriesForProcessingResults();
String timeZone = messageService.getMessage("org.default_timezone", null, Locale.getDefault());
if(lstOfExams!=null&&!lstOfExams.isEmpty()){
ThreadPoolTaskExecutor threadPoolExecuter = new ThreadPoolTaskExecutor();
threadPoolExecuter.setCorePoolSize(lstOfExams.size());
threadPoolExecuter.setMaxPoolSize(lstOfExams.size()+1);
threadPoolExecuter.setBeanName("ThreadPoolTaskExecutor");
threadPoolExecuter.setQueueCapacity(100);
threadPoolExecuter.setThreadNamePrefix("ThreadForUpdateExamResult");
threadPoolExecuter.initialize();
for(Object[] obj : lstOfExams){
if(StringUtils.isNotBlank((String)obj[2]) ){
timeZone = obj[2].toString();
}
try {
Userexams userexams=examService.findUserExamById(Long.valueOf(obj[0].toString()));
if(userexams.getExamresult()==null){
UpdateUserExamDataThread task=new UpdateUserExamDataThread(obj,timeZone);
threadPoolExecuter.submit(task);
}
// testEvaluator.generateTestResultAsPerEvaluator(Long.valueOf(obj[0].toString()), obj[4].toString(), obj[3]==null?null:obj[3].toString(),timeZone ,obj[5].toString() ,obj[1].toString());
// logger.error("Percentage Marks:::::"+result.getPercentageCatScore());
} catch (Exception e) {
Log.error("Exception at ResultProcessingJob extends QuartzJobBean …Run Code Online (Sandbox Code Playgroud) 我要求异步执行任务,同时丢弃任何进一步的请求,直到任务完成.
同步方法只是将任务排队,不会跳过.我最初想过使用SingleThreadExecutor,但也排队等待任务.然后我查看了ThreadPoolExecutor,但是它读取队列以获取要执行的任务,因此将执行一个任务并且至少有一个任务排队(其他任务可以使用ThreadPoolExecutor.DiscardPolicy丢弃).
我唯一能想到的就是使用信号量来阻止队列.我带着以下示例来展示我想要实现的目标.有更简单的方法吗?我错过了一些明显的事吗?
import java.util.concurrent.*;
public class ThreadPoolTester {
private static ExecutorService executor = Executors.newSingleThreadExecutor();
private static Semaphore processEntry = new Semaphore(1);
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 20; i++) {
kickOffEntry(i);
Thread.sleep(200);
}
executor.shutdown();
}
private static void kickOffEntry(final int index) {
if (!processEntry.tryAcquire()) return;
executor.
submit(
new Callable<Void>() {
public Void call() throws InterruptedException {
try {
System.out.println("start " + index);
Thread.sleep(1000); // pretend to do work
System.out.println("stop " …Run Code Online (Sandbox Code Playgroud) 我有一项任务,我想以固定的速度运行.但是,每次执行后我还需要任务的结果.这是我尝试过的:
任务
class ScheduledWork implements Callable<String>
{
public String call()
{
//do the task and return the result as a String
}
}
Run Code Online (Sandbox Code Playgroud)
不,我试图使用它ScheduledExecutorService来安排它.事实证明,你不能Callable以固定的速度安排,只有一个Runnable可以这样做.
请指教.
我正在阅读CyclicBarrier以下链接
http://java-latte.blogspot.in/2013/10/cyclicbarrier-in-java-concurrency.html.
在示例1中,CyclicRaceDemo.javamain方法,CyclicBarrier正在重用而不调用reset方法.
我运行了这个例子,它运行良好.所以,我想知道reset方法的用途是什么.应该什么时候打电话?或者我们需要打电话吗?
java concurrency multithreading java.util.concurrent cyclicbarrier
将2000万个实体推入java地图对象的最佳方法是什么?
我相信这两项任务都在两个不同的核心中运行.问题:当我创建一个推送1000万个数据的任务时,需要大约9秒,然后当运行2个任务时,每个任务都会推送1000万个数据,为什么需要大约26秒?难道我做错了什么 ?
在不到10秒的时间内插入20 M数据是否有不同的解决方案?