代码:
Map<Integer,DealCountUpdater> dealCountMap=new HashMap<Integer,DealCountUpdater>();
public void update(){
for(Map.Entry<Integer, DealCountUpdater> e:new HashMap<Integer,DealCountUpdater>(dealCountMap).entrySet()){//line:58
System.out.println(e.hashCode());
}
}
Run Code Online (Sandbox Code Playgroud)
当我运行此代码时,出现以下异常:
java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(HashMap.java:793)
at java.util.HashMap$EntryIterator.next(HashMap.java:834)
at java.util.HashMap$EntryIterator.next(HashMap.java:832)
at java.util.HashMap.putAllForCreate(HashMap.java:435)
at java.util.HashMap.<init>(HashMap.java:225)
at org.my.tuan.count.CountUpdater.update(CountUpdater.java:58)
at org.my.tuan._Maintainer.run(TuanSched.java:110)
Run Code Online (Sandbox Code Playgroud)
这一行是 CountUpdater.java:58 :
for(Map.Entry<Integer, DealCountUpdater> e:new HashMap<Integer,DealCountUpdater>(dealCountMap).entrySet()){
Run Code Online (Sandbox Code Playgroud)
我谷歌这个程序,我知道我可以使用一个ConcurrentHashMap而不是一个普通的HashMap,
但我想知道,为什么我使用:
new HashMap<Integer,DealCountUpdater>(dealCountMap)
Run Code Online (Sandbox Code Playgroud)
为 HashMap 创建新实例,仍然抛出ConcurrentModificationException?
如何通过不使用来修复它ConcurrentHashMap?
感谢帮助 :)
我需要处理检索挂起的记录,并将它们更新为工作单元的“处理中”状态。我想确保下面的代码支持并发,其他线程要等到我当前的线程处理完毕。实现此目标的最佳方法是什么?
public Collection<Object> processPendingMessages() {
Collection<Object> messages = null;
//Retrieve pending messages
messages = messageDAO.getPendingMessages(Direction.INBOUND);
//Update pending messages to Inprocess
if (messages!=null && messages.size()>0) {
messageDAO.updateMessagesToInprocess(messages);
}
return messages;
}
Run Code Online (Sandbox Code Playgroud)
非常感谢您的投入。谢谢。
我在Solaris 10上运行Java 1.5.我的程序是一个独立的java程序,使用java并发包和log4j-1.2.12.jar来记录某些信息.主要逻辑如下
ExecutorService executor = new AppThreadPoolExecutor(10, 10, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(Integer.MAX_VALUE), new AppThreadFactory("BSRT", true), new ThreadPoolExecutor.CallerRunsPolicy());
CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(executor);
for (final Integer id : taskList) {
Callable<Integer> c = new Callable<Integer>() {
public Integer call() throws Exception {
int newId = DB operation(id);
return newId;
}
};
completionService.submit(c);
}
logger.debug("Start retrievie result");
for (Integer id : taskList) {
try {
Future<Integer> future = completionService.poll(1, TimeUnit.SECONDS);
Integer taskId=null;
if (future != null) {
logger.debug("future is obtained.");
taskId …Run Code Online (Sandbox Code Playgroud) 我正在尝试学习java并发API,对于我的练习,我想安排一个作业每隔X秒定期运行一次.该作业将计算随机数.
我想在完成后立即获得计划任务的结果.我无法仅使用API完成此操作,因此我将其破解.
有没有办法更好地做到这一点,而不使用低级机制?我希望能够删除同步MyRandomGiverTask.getResult(),而是使用类似的东西ScheduledFuture.get().但在我的代码中,ScheduledFuture永远不会完成/完成.这是我目前的解决方案:
class A {
public static void main() {
MyRandomGiverTask task = new MyRandomGiverTask(200);
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
ScheduledFuture<Double> scheduledDouble =
(ScheduledFuture<Double>) scheduler
.scheduleAtFixedRate(task, 1, 4, TimeUnit.SECONDS);
while (true) {
System.out.println(" >> " + task.getResult());
}
}
public class MyRandomGiverTask implements Runnable {
MyRandomGiver giver = new MyRandomGiver();
int param;
double result;
public MyRandomGiverTask(int param) { this.param = param; }
@Override public void run() { result = giver.getRandom(param); }
public double getResult() {
try …Run Code Online (Sandbox Code Playgroud) java concurrency scheduling scheduled-tasks java.util.concurrent
你好.
我正在运行服务器并添加了一个迷你游戏.
每当游戏即将开始时......它首先调用onStart().现在我在这一行得到ConcurrentModificationException:
for(Player p : waiting) {
Run Code Online (Sandbox Code Playgroud)
这是方法:
public void onStart() {
trawler.players.clear();
for(Player p : waiting) {
if(!boat.playerInArea(p)) {
waiting.remove(p);
}
}
for(Player p : waiting) {
trawler.players.add(p);
}
trawler.start();
waiting.clear();
}
Run Code Online (Sandbox Code Playgroud)
如果你需要课程,这里是:
TrawlerWaitingRoom.java:
package server.model.minigames.trawler;
import server.model.players.Location;
import server.model.players.Player;
public class TrawlerWaitingRoom extends WaitingRoom {
private Trawler trawler;
//private Location boat = new Location(2668,2674,3165,3185);
private Location boat = new Location(2808, 2811,3415,3425);
public TrawlerWaitingRoom(Trawler trawler) {
super(1, 2);
this.trawler = trawler;
}
@Override
public boolean startGame() {
if(trawler.inProgress()) …Run Code Online (Sandbox Code Playgroud) 这就是我想要实现的目标:我想要一些对象(可能是某种执行器),我可以提交一系列要执行的任务(比如说List<Callable<T>>).当所有这些任务都已完成运行时,我希望得到通知(可能通过Future对象中可用的值).
这个"执行者"应该能够同时处理几个批次.换句话说:两个(或更多)代码站点可以提交两个不同的批次,并且只有当"他的"批次结束时才会通知每个站点.
更好的是,我希望这Future能为我提供一个List<T>由各种任务返回的值Callable.
总结以上内容我正在寻找能够在概念上与以下内容完全相同的API:
public T Future<List<T>> submitBatch(List<Callable<T>> tasks)
Run Code Online (Sandbox Code Playgroud)
什么罐头结构java.util.concurrent可以帮助我实现最大化?
我在for循环中创建了几个线程,如下所示:
for (int i = 0; i<5; i++) {
new Thread() {
//do stuff
}
}
Run Code Online (Sandbox Code Playgroud)
但我需要确保这些线程一个接一个地执行,而不是同时执行.
做这个的最好方式是什么?
java concurrency multithreading executorservice java.util.concurrent
我发现几乎所有高级同步抽象(例如Semaphore,CountDownLatch,java.util.concurrent中的Exchanger)和并发集合都使用Unsafe中的方法(例如compareAndSwapInt方法)来定义关键部分。同时,我希望同步块或方法将用于此目的。您能否解释一下,不安全方法(我的意思是仅可以原子设置值的方法)比同步更有效,为什么会这样呢?
我想在 java 中创建一个固定大小的队列,我只想在队列中存储最多 10 个对象。但是,队列继续存储/添加对象并忽略if条件。
我的代码:
Queue<Customer> sitt = new LinkedList<Customer>();
if(sitt.size() < 10) {
System.out.println("Added");
((LinkedList<Customer>)sitt).offer(cust);
}else {
System.out.println("No space..");
}
Run Code Online (Sandbox Code Playgroud)
我有另一个 Runnable 类,我正在运行 22 个线程。此条件应仅添加0-9Customer 类的对象。但是,sitt.size()甚至超过了 20。谁能告诉我这里有什么问题?甚至连if条件都被忽略了。
PS:我在这里使用 Queue 的原因是因为我需要 FIFO。
什么是更好的选择,为什么?该地图用作临时存储。它将项目保留一段时间,然后刷新到 db。
这是我用原子参考实现的虚拟代码:
public class Service {
private final AtomicReference<Map<String, Entity>> storedEntities = new AtomicReference<>(new HashMap<>());
private final AtomicReference<Map<String, Entity>> newEntities = new AtomicReference<>(new HashMap<>());
private final Dao dao;
public Service(Dao dao) {
this.dao = dao;
}
@Transactional
@Async
public CompletableFuture<Void> save() {
Map<String, Entity> map = newEntities.getAndSet(new HashMap<>());
return dao.saveAsync(map.values());
}
@Transactional(readOnly = true)
@Async
public CompletableFuture<Map<String, Entity>> readAll() {
return dao.getAllAsync().thenApply(map -> {
storedEntities.set(map);
return map;
});
}
@Scheduled(cron = "${cron}")
public void refreshNow() {
save();
readAll();
} …Run Code Online (Sandbox Code Playgroud)