java,multithreading,java.util.concurrent
I am answering my own question, rather than deleting the question, as the information might prove useful for others if a problem with ConcurrentSkipListSet comes up. My error proved to be a poorly written implementation of Comparable. There are requirements listed in the JavaDoc that are supposed to be enforced...
java,multithreading,concurrency,executorservice,java.util.concurrent
If you put the code inside the thread run() function and make the function synchronized, it will make sure that only one thread can run at a time. Here's the code: public static void main(String[] args) { for (int i = 0; i < 5; i++) { Thread thread =...
java,concurrency,java.util.concurrent
The trick is to use .handle((r, e) -> r) to suppress the error: CompletableFuture.runAsync(() -> { throw new RuntimeException(); }) //Suppress error .handle((r, e) -> r) .thenCompose((r) -> CompletableFuture.runAsync(() -> System.out.println("HELLO"))); ...
java,android,runnable,java.util.concurrent,concurrent-programming
Try this code, //Kept at class level private Runnable r; private Handler temp; introButton = (Button) findViewById(R.id.introButtonID); introButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub startActivity(); } }); r=new Runnable() { @Override public void run() { // TODO Auto-generated method stub startActivity(); } };...
java,multithreading,java.util.concurrent
You can use the scheduleAtFixedRate(control, 10l, 1l, TimeUnit.SEDONDS) scheduler to create and execute new tasks (in other threads), similar to: final ScheduledExecutorService pool = new ScheduledThreadPoolExecutor(100); Runnable control = new Runnable() { public void run() { Runnable task = new Runnable() { public void run() { // do work here...
java,multithreading,serialization,concurrency,java.util.concurrent
Why do you need the Thread.sleep(50) ? This is what's making the concurrent execution into a sequential one, especially if each each computation is <= 50 ms. My guess is that deserialization time + computation time is longer than 50 ms, which would be why in the deserialized objects scenario...
java,multithreading,java.util.concurrent
Thread safety for a synchronized collection only applies to one method call. Between method calls the lock is released and another thread can lock the collection. If you perform two operations, anything could happen in the meantime, unless you lock it your self. e.g. // to add two elements in...
java,concurrency,java.util.concurrent
Caffeine uses lazy or relaxed writes in many of its data structures. When nulling out a field (e.g. ConcurrentLinkedStack) When writing to volatile fields before publishing (e.g. SingleConsumerQueue) When publish is safely delayable (e.g. BoundedBuffer) When races are benign (e.g. cache expiration timestamps) When inside a lock (e.g. BoundedLocalCache) ConcurrentLinkedQueue...
java,concurrency,java.util.concurrent,forkjoinpool
You're confused? Everyone is confused. I've been writing a critique on the F/J framework for four years now and I can tell you the level of complexity is reaching the critical level with 8u40. The reason this class exists at all is because the join() doesn't work. In order to...
The problem is that your Runnable is not interruptible: task interruption is a collaborative process in Java and the cancelled code needs to check regularly if it's been cancelled otherwise it won't respond to the interruption. You can amend you code as follows and it should work as expected: Runnable...
java,threadpool,lazy-evaluation,java.util.concurrent,short-circuiting
Here's an implementation of ParallelOr using ExecutorCompletionService. It waits on tasks until one returns true. If none do, it eventually returns false. public class ParallelOr { static class LongTask implements Callable<Boolean> { private int milliseconds; private boolean val; public LongTask(int milliseconds, boolean val) { this.milliseconds = milliseconds; this.val = val;...
java,memory-leaks,jvm,java.util.concurrent
As the8472 pointed, analyzed the dump and observed that it is not an issue with ConcurrentLinkedQueue's poll() and offer() methods. In our architecture, concurrentLinkedQueue acts as a buffer in which logs are piled up and a DBPushThread will fetch the logs from CL Queue and insert them to backend storage....
java,multithreading,priority-queue,java.util.concurrent,round-robin
I feel like it's more straightforward to implement this with one Queue for each producer. One thread can't wait on multiple Queues, but you could combine all of the Queues into one helper class so that it doesn't need to. import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map;...
java,concurrency,java.util.concurrent
Your AsyncQueue is very similar to a BlockingQueue such as ArrayBlockingQueue. The Future returned would simply delegate to the ArrayBlockingQueue methods. Future.get would call blockingQueue.poll for instance. As for your update, I'm assuming the thread that calls add should invoke the callback if there's one waiting? If so it's a...
java,locking,java.util.concurrent
I suspect the difference is because of the different semantics of offer() and put(). From the javadoc: offer(E e) Inserts the specified element at the tail of this queue if it is possible to do so immediately without exceeding the queue's capacity, returning true upon success and false if this...
java,multithreading,java.util.concurrent,blockingqueue
It does not block, it simply does not enter in the loop branch. You can easily check: LinkedBlockingQueue<Integer> queue = new LinkedBlockingQueue<>(); for (Object obj : queue) { System.out.println("Inside the loop, is empty? " + queue.isEmpty()); } System.out.println("Not blocking, is empty? " + queue.isEmpty()); Output: Not blocking, is empty? true...
java,thread-safety,java.util.concurrent,concurrenthashmap
The remove method does synchronize on a lock. Indeed checking the code of ConcurrentHashMap#remove(), there is a call to a lock method that acquires the lock: public V remove(Object key) { int hash = hash(key.hashCode()); return segmentFor(hash).remove(key, hash, null); } where ConcurrentHashMap.Segment#remove(key, hash, null) is defined as: V remove(Object key,...
java,multithreading,apache-httpclient-4.x,java.util.concurrent
You can toggle re-use of connections within the pool using the builder's setConnectionReuseStrategy. The DefaultConnectionReuseStrategy will re-use connections whenever possible, but the NoConnectionReuseStrategy will close all connections returned to the pool. I used these connection re-use strategies in reverse: in production no re-use was set (to ensure proper load-balancing -...
runnable,java.util.concurrent,callable,threadpoolexecutor
What happens is that ThreadPoolExecutor does not add your Callable to the queue directly. Instead, it will wrap the Callable into a RunnableFuture via a call to the method AbstractExecutorService.newTaskFor(Callable), then add this RunnableFutureto the queue.
java,multithreading,concurrency,java.util.concurrent
You can replace the synchronized block by: private final AtomicBoolean flag = new AtomicBoolean(); while (!flag.compareAndSet(false, true)); try { //your code here } finally { flag.set(false); } You should test both under your contention scenario to make sure that it does actually improve performance. CAS works best under small to...
java,multithreading,java.util.concurrent
There are so many things wrong with this. Firstly, you expect it to contain 0..9, but you call count++ before al.add(count), which means you should actually expect 1..10. Since you're using a new LockWithSynchronize or Locking each time, there isn't actually any shared lock -- each instance gets its own...
android,hashmap,java.util.concurrent,concurrenthashmap
If you are using ConcurrentHashMap, then there is not point it will not work. I strongly doubt that you are trying to access wrong index or you do not have synchronization between inserting and accessing the particular index. For that just check the size of udata and value of xcor...
java,for-loop,concurrency,java.util.concurrent,concurrent-programming
Read up on streams, they're all the new rage. Pay especially close attention to the bit about parallelism: "Processing elements with an explicit for-loop is inherently serial. Streams facilitate parallel execution by reframing the computation as a pipeline of aggregate operations, rather than as imperative operations on each individual element....
java,multithreading,jdbc,spring-batch,java.util.concurrent
Whilst this does not directly answer your exact question, I would encourage you to review your data structure. You have used the Adjacency List Model which, whist simple to implement initially, opens a whole ugly can of worms when it comes to querying. There are other models to consider, such...
java,multithreading,servlets,concurrency,java.util.concurrent
The line request.getRequestDispatcher(JSP_PAGE).forward(request, response); forwards to an JSP page. The error may be inside of that JSP as well (the part of the stacktrace may hide the original error)...
java,multithreading,java.util.concurrent
I don't know what StringTask is, but you seem to be passing the full list of URLs to it. Make the appropriate changes to only submit a single URL from the list pool.submit(new StringTask(fileList.get(i))); (Or use an iterator over the fileList, whichever is more appropriate for a CopyOnWriteArrayList.) for (String...
java,java.util.concurrent,threadpoolexecutor
Yes it is possible to retry the execution of the rejected task. The best way to retry the execution is to use an alternate executor. You may declare a custom RejectedExecutionHandler class simply like as you do this with other interfaces. Here are some code samples: public class MyRejectedExecutionHandler implements...
java,multithreading,concurrency,java.util.concurrent,cyclicbarrier
A CyclicBarrier is cyclic because it can be reused without resetting. From the Javadoc A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point. CyclicBarriers are useful in programs involving a fixed sized party of threads that must occasionally...
java,java.util.concurrent,concurrenthashmap
From the source code, freely available and coming with the JDK: if (initialCapacity < concurrencyLevel) // Use at least as many bins initialCapacity = concurrencyLevel; // as estimated threads So, in short, if you pass arguments that don't make sense, it fixes it for you....
java,multithreading,executorservice,java.util.concurrent
ExecutorService runs jobs in parallel, but does not automatically make it safe to concurrently access shared state across threads. So, "yes" to both parts of your question. The problem is caused, in part, by the two runnables sharing the same FinTrans state object. The other part of the problem is...
java,multithreading,java.util.concurrent
Without knowing details about the load your system has, environment it is using and how long does it take to process one message it is hard to say which number of threads you need. However, you can think of the following base principles: Having many threads is bad, because you'll...
jetty,cpu-usage,java.util.concurrent
You state you do run the ExecutorService part on a different machine, but the URL is http://localhost:8080. That's a no-no in load testing. Some advice: Don't have the Client Load and the Server Load on the same machine (don't cheat and attempt to put the load on 2 different VMs...
java,multithreading,collections,java.util.concurrent
What makes you think you need additional synchronization? I don't see why that would be the case. One thing I would change is that addSubscription should check if the set for the given server is absent, and add it atomically. This way you avoid a race condition when two threads...
One How many threads varies, not by CPU, but by what you are doing. If, for example, what you are doing with your threads is highly disk intensive, your CPU isn't likely to be maxed out, so doing 8 threads may just cause heavy thrashing. If, however, you have...
java,multithreading,java.util.concurrent
OK, so you have a class which gets you some data from a web page in a blocking way, and takes some arguments: public class DataFetcher { public Data fetchData(int param1, int param2) { // ... } } And now you want to execute this method twice, concurrently, and get...
java,concurrency,documentation,future,java.util.concurrent
After cancel(...), isDone() should always be true. It doesn't matter what cancel(...) returned. If cancel(...) returns true it means this future is now cancelled and isCancelled()==true If cancel(...) returns false it means that the completion was not due to this call to cancel() cancel(false) means that the cancel method...
java,concurrency,java.util.concurrent
Never use java.util.concurrent.Future. Use com.google.common.util.concurrent.ListenableFuture or similar instead. With ListenableFutures you can register callbacks when a ListenableFuture completes: ListenableFuture<Integer> future = MoreExecutors.listeningDecorator(executor).submit( new Callable<Integer>() { @Override public Integer call() throws Exception { ... } }); // Add jobId to the map. You should use a thread-safe Map! map.put(jobId, future); Futures.addCallback(future,...
scala,concurrency,java.util.concurrent
blocking is meant to act as a hint to the ExecutionContext that the contained code is blocking and could lead to thread starvation. This will give the thread pool a chance to spawn new threads in order to prevent starvation. This is what is meant by "adjust the runtime behavior"....
java,multithreading,concurrency,java.util.concurrent
From the ScheduledThreadPoolExecutor (the actual type returned by Executors.newScheduledThreadPool) documentation: When a submitted task is cancelled before it is run, execution is suppressed. By default, such a cancelled task is not automatically removed from the work queue until its delay elapses. While this enables further inspection and monitoring, it may...
java,multithreading,executorservice,java.util.concurrent
According to Thread javadoc: The Java Virtual Machine continues to execute threads until either of the following occurs: The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place. All threads that are not daemon threads have died, either by...
java-7,executorservice,java.util.concurrent
This behavior you observe is indeed the expected one. Consider the following: 1) Task3 counts up to Integer.MAX_VALUE - 5000, whereas Task1 and Task2 count up to Long.MAX_VALUE - 5000. All things being equal, this means that Task1 and Task2 will last 2^32 times longer than Task3, that's over 4...
The compiler adds a synthetic bridge method to support generics. So @Override public String call() throws Exception { Thread.dumpStack(); return "Hello "+who+" from callable"; } in the compiled .class file is really two methods // actual method public Object call() throws Exception { return call(); // the other call }...
java,hashmap,hashtable,java.util.concurrent
How about private ConcurrentSkipListMap<Optional<Date>, T> map; ? Then to add elements: map.put(Optional.fromNullable(date), value); And when accessing key check Optional.isPresent() and call Optional.get(). http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Optional.html...
It is quite possible (and in a multithreaded environment quite common) for get to be called many times by many threads. If you wish to implement Future<V> you must implement the complete contract - including: Future... The result can only be retrieved using method get when the computation has completed,...
java,multithreading,java.util.concurrent,concurrenthashmap,concurrentmodification
I also managed to reproduce such case on my machine. I think, the problem is that EntrySetView (which is returned by ConcurrentHashMap.entrySet()) inherits its removeIf implementation from Collection, and it looks like: default boolean removeIf(Predicate<? super E> filter) { Objects.requireNonNull(filter); boolean removed = false; final Iterator<E> each = iterator(); while...
java,concurrency,java-8,java.util.concurrent
You are using TreeSet.addAll() inside the forEach of parallel stream. The forEach body can be executed simultaneously several times in different threads for different elements and TreeSet is not thread-safe. To fix the problem quickly you can either synchronize modification of result or use forEachOrdered. However it would be cleaner...
java,client-server,java.util.concurrent,concurrent-programming
That depends what you mean by best solution. If you just want your program to behave correctly in a concurrent environment, then you should synchronize data that is concurrently modified. That would be a standard (and readable) way to enable exclusive access to shared data. However, if this is not...
java,concurrency,java.util.concurrent,reentrantreadwritelock
As far as the question is concerned: your usage of ReentrantReadWriteLock is correct. With regard to your problem: I think you need to look toward the transaction isolation level in effect (and possibly adjust it). Hope this helps... Isolation levels explanation in another SO thread: what is difference between non-repeatable...
java,multithreading,asynchronous,concurrency,java.util.concurrent
What I want is a minimum thread pool size and a maximum thread pool size that queues up work and lets threads go idle when there is no work. This is precicely what a fixed-thread pool with unbounded queue gives you. In short defining a thread-pool like new ThreadPoolExecutor(...
java,java.util.concurrent,memory-visibility
A: If the object is immutable or if the object is mutable but all the properties are set before the object is added to the collection then yes, they will be all visible. B: If no synchronisation mechanisms are in place then it is not guaranteed, it depends when the...
java,executorservice,java.util.concurrent
Simply transform the runnables into callables: List<Callable<Void>> callables = new ArrayList<>(); for (Runnable r : runnables) { callables.add(toCallable(r)); } executor.invokeAll(callables); private Callable<Void> toCallable(final Runnable runnable) { return new Callable<Void>() { @Override public Void call() { runnable.run(); return null; } }; } ...