Questions tagged [java.util.concurrent]

Java package which contains utility classes commonly useful in concurrent programming. This package includes a few small standardized extensible frameworks, as well as some classes that provide useful functionality and are otherwise tedious or difficult to implement.

Filter by
Sorted by
Tagged with
1 vote
1 answer
233 views

IntelliJ IDEA + JDK 21 issue with java.util.concurrent package - TimeUnit class not available

I have an issue when I am trying to use TimeUnit class from java.util.concurrent. It happens with Oracle JDK 21.0.1 (configurations are below) + IntelliJ IDEA 2023.1.5 (Community Edition) - the latest ...
rsnlpn's user avatar
  • 143
0 votes
1 answer
47 views

What's wrong with my function for making async calls to an endpoint and collecting responses?

I have a use-case where I need to hit an endpoint to fetch some data. The endpoint takes start-date-time and end-date-time as params and has a limitation that the duration between them can only be <...
mysteryFruit's user avatar
0 votes
0 answers
35 views

Java Socket on Localhost - Server thread number drops after a while and causes Connections timeout

Background I'm learning Java Socket on my own. I created a Socket Server and Client to run on localhost. Server uses a fixed-size threadpool of size 20 to handle connections. Client creates 50 ...
Wanda's user avatar
  • 1
0 votes
2 answers
58 views

Using Future blocks UI in application

In my Android app I want to use java.util.concurrent tools to make operations that return value (for educational purposes). I read that CompletableFuture can be used for this. I made a project where I ...
faritowich's user avatar
-2 votes
1 answer
23 views

Idiom for 2 argument version of Condition#await(long, TimeUnit)

What's the idiomatic way of handling spurious wakeups when using the 2 argument version of Condition#await(long, TimeUnit) I understand the zero argument version: import java.util.concurrent.Executors;...
David O'Loughlin's user avatar
0 votes
1 answer
46 views

How does the jvm return a Future object reference before the asynchronous method has completed

Consider the following code class Test { public void method1() { CompletableFuture<String> future = helloFuture(); assertEquals("done", future.get()); } } class Service { ...
Abe's user avatar
  • 8,691
0 votes
1 answer
47 views

How to ensure thread safety for Java reflection's set operation?

Is Field public void set(Object obj, Object value) thread-safe when using Java reflection? If it's not thread-safe, how can the atomicity of set be ensured? Write rarely and read frequently, reads and ...
xiao chen's user avatar
3 votes
1 answer
106 views

Why does the 'execute' method of ExecutorService in applyAsync run on main thread sometimes

I have overridden the execute method for java.util.concurrent.Executor in ThreadPoolExecutor implementation. The new implementation just decorates the runnable and then calls the original execute. The ...
nluk's user avatar
  • 684
0 votes
1 answer
39 views

j.u.c.ConcurrentHashMap - What is baseCount and sumCount?

I am trying to understand the implementation of CHM in Java. Two fields are used when resizing operations are taking place: baseCount sumCount() function baseCount is described as : / ** * ...
ng.newbie's user avatar
  • 2,910
2 votes
1 answer
70 views

ConcurrentHashMap - Can we get rid of i >= n from transfer()?

Related to : In ConcurrentHashMap's transfer method, I don't understand the meaning of these two conditions "i >= n" and "i + n >= nextn" I am looking into the ...
ng.newbie's user avatar
  • 2,910
2 votes
1 answer
39 views

Jenkins concurrent builds archive artifacts

When I trigger concurrent builds in jenkins, only the later finishing build artifacts not archiving. It says, Archiving artifacts ‘workspace-2/results*/’ doesn’t match anything, but ‘’ does. Perhaps ...
Sachin Liyanage's user avatar
1 vote
1 answer
48 views

Should I use lock for reference assignment in class

I have a Spring component class with field of type list with fill from AWS DynamoDB. The use of this component class is in a controller for reading the list. I also have a schedule service that run in ...
eweiss's user avatar
  • 51
0 votes
1 answer
41 views

Using ScheduledExecutorService drastically slows down execution

I need to limit the execution time of some methods so am using ScheduledExecutorService not to add concurrency but to enforce a timeout. public class Task { private static final ...
Ellen Spertus's user avatar
0 votes
2 answers
79 views

How to ensure an unique item/object is picked from the collection in multi-threading scenario?

I have a collection of string values available. I thought of using CopyOnwriteArrayList or ConcurrentLinkedQueue initially. But, when I run my code, I see that same string values are picked by one ...
Rahul Raj's user avatar
  • 3,237
0 votes
1 answer
76 views

How to determine coreThreadSize if having multiple threadpools in application

There are a lot of online resources showing how to determine best coreThreadSize when working with a SINGLE threadpool.Brian Goetz in his famous book "Java Concurrency in Practice" ...
Drex's user avatar
  • 3,491
0 votes
1 answer
158 views

Future.get() throws java.util.concurrent.ExecutionException: java.util.ConcurrentModificationException

I have a list of recodes called filterRecords -> List<Tuple<String, GenericRecord>> filterRecords. I am splitting this list into sub lists and giving each sublists to a separate thread ...
Ishan Tiwary's user avatar
0 votes
1 answer
85 views

Apache nifi concurrent task

How Nifi uses concurrency framework to achieve parallelism. nifi concurrent task If I assign concurrent task to 5. At a time five flowfile will be processed by nifi processor,then onTrigger is called ...
Sathish 's user avatar
0 votes
1 answer
115 views

java.util.concurrent.ExecutorService.awaitTermination() doesn't work as expected

I have a problem. The code that follows pool.awaitTermination() is not executed. ExecutorService pool = Executors.newFixedThreadPool(6); for (HierarchyItem rootItem : rootObjectItems) ...
Елена Ковалинская's user avatar
0 votes
0 answers
47 views

How to manage threads with locks and custom condition with Spring?

In a Spring application the goal is to have multiple threads running, 1 of each "type" at a time. When running together type1, type2, type3, type3, only the first 3 are running (...
wp42's user avatar
  • 158
-2 votes
2 answers
53 views

Iterating over a list of user defined class using Iterator class of enhanced for loop gives java.util.ConcurrentModificationException

Iterating over a list of user defined class using Iterator class of enhanced for loop gives java.util.ConcurrentModificationException exception but when using the traditional for loop it runs just ...
alamshahbaz16497's user avatar
1 vote
1 answer
72 views

How to maintain atomicity with ConcurrentHashMap get and put methods?

In a multi-threaded environment, I am performing get and put operations on a ConcurrentHashMap implementation. However, the results are un-expected. Please find below code and output. import java.util....
Pushpak's user avatar
  • 147
2 votes
0 answers
270 views

Parallel Stream with virtual threads: Java VirtualThread equivalent for ForkJoinWorkerThread

I'm experimenting with Java virtual threads and wonder if it's possible to run parallel Streams with virtual threads. By default, parallel streams are run on the common ForkJoinPool, but one could use ...
Warren Nocos's user avatar
  • 1,252
2 votes
2 answers
128 views

ComputeIfAbsent wrong map size

I have tried below code in order to have a unique id for each jj. As far as I know, computeIfAbsent is thread-safe but: public static void main(String[] args) throws InterruptedException { ...
Ahmad Darwich's user avatar
0 votes
0 answers
54 views

Avoid cost of volatile value in AtomicReference

Thread 1 -> Compute a value MyObject and store in AtomicReference< MyObject>> Thread 2 -> Would sometimes need the value of MyObject stored by Thread 1 Looking at AtomicReference::set ...
Novice User's user avatar
  • 3,604
0 votes
1 answer
43 views

applying concurrency when a ConcurrentHashMap is map value

Multiple threads will try to update values of same mainCode, does below cause trouble? Also another job will consistently read values of securities and apply operations if values match. public class ...
SmokingTurtle's user avatar
1 vote
1 answer
546 views

ANR crash (sun.misc.Unsafe.park(Native method))

main (timed waiting):tid=1 systid=22386 at sun.misc.Unsafe.park(Native method) at java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:230) at kotlinx.coroutines....
Maradiya Krupa's user avatar
0 votes
1 answer
886 views

java.util.concurrent.TimeoutException executing parallels scenarios in Selenium Grid in Docker

Our Automation project is written in Java, and we are using the following libraries: Cucumber 3.1.6 Selenium 4.0.0 awaitility 3.1.6 We are executing several Jenkins jobs in parallel, in a Selenium ...
xyuste's user avatar
  • 1
0 votes
0 answers
42 views

Is there any chance that even though the lock object is free thread fails to acquire the lock?

I'm working on multithreading issue where threads failed to acquire the lock even though the lock is free i.e., none of the threads acquire the lock I'm using java.util.concurrent.locks.ReentrantLock....
vishal's user avatar
  • 23
1 vote
3 answers
83 views

Creating a shallow copy of a concurrent collection in Java

I want to create a shallow copy of a concurrent collection, turning it into a regular collection. Is there a problem with doing it like this: ledger = new ConcurrentLinkedDeque<>(); // this line ...
chilliefiber's user avatar
0 votes
1 answer
54 views

when do we really benfit from java stream.unordered()? [duplicate]

java streams has this method unordered(). I am not sure when this method will really enhance the performance of the program. someList.stream.unordered() //here List is any way ordered and using ...
samshers's user avatar
  • 3,119
0 votes
1 answer
45 views

Why ForkJoinTask.join() call rather block the thread instead of stealing the work as expected from work stealing mechanism

I have a recursive task which splits asymmetrically. Instead of splitting in halves it rather bites a pice of work it can execute and forks the rest of work. Such scenario does not get paralleled as ...
Alex Gal's user avatar
0 votes
1 answer
129 views

what is the difference between CompletableFuture methods acceptEither vs acceptEitherAsync?

For example - CompletableFuture.supplyAsync(stage1).acceptEither(stage2, consumer ); stage1 and stage2 are supposed to run in parallel in above code as it is using acceptEither If I change to ...
samshers's user avatar
  • 3,119
0 votes
1 answer
318 views

CompletableFuture thenApply is running in seperate thread not on caller thread?

When I execute thenApply method of a CompletableFuture, the execution of this method is happening in the ForkJoinPool thread, not on caller (main) thread. Why is it so? This result i.e using the fork ...
samshers's user avatar
  • 3,119
0 votes
0 answers
172 views

CompletableFuture - Aggregating many results from a list for a Saga Fan-Out Pattern?

I'm trying to model a fan-out saga pattern in a Java 11 spring component. The goal is to use the java concurrency classes to track the aggregate result status for many requests which are tracked in a ...
emeraldjava's user avatar
0 votes
1 answer
152 views

Hibernate ConcurrentModificationException problem in Stress testing

There is an application with the following configuration: 1- HK2 for DI 2- Hibernate for ORM and 3- GrizzlyHttpServer and the its hibernate configuration is : import org.hibernate.*; import org....
reza ramezani matin's user avatar
0 votes
0 answers
255 views

How to apply a thread-safe JSONObject or JSONArray in org.json package?

Using ExecutorService I am trying to concurrently create a JSONObject of type org.json, which in turn it contains a JSONArray. However, org.json is not defining thread-safe Json. How can I write the ...
Shila Mosammami's user avatar
0 votes
2 answers
69 views

Java Thread Safety of Enum ValueOf

I have what most likely is a dumb question regarding thread safety. I have a ENUM class where I have valuesof defined like so: public enum ThirdPartyContentSource { DEV_TO("DevTo"), ...
MetaCoder's user avatar
  • 378
0 votes
0 answers
82 views

When a thread is reading a json file, how to make sure all other threads are in wait in java?

I'm creating dynamic threads as shown below ExecutorService service = Executors.newFixedThreadPool(brnchCount); Semaphore smp = new Semaphore(1); for (Object o : list) { service.submit(new MyTask(o, ...
Eswari Sekar's user avatar
0 votes
0 answers
32 views

CyclicBarrier not working properly as I expected and showing different result

I was just trying to run multiple threads with CyclicBarrier limit:3 but threads are run more or less than limit . In CyclicBarrierDemo (in main thread) I create CyclicBarrier object with limit 3 and ...
axel's user avatar
  • 11
-2 votes
1 answer
116 views

Why does this code get stuck in infinite loop [closed]

public void bad() { final ConcurrentMap<String, Integer> chm = new ConcurrentHashMap<>(); final String key = "1"; chm.computeIfAbsent(key, __ -> { ...
ECPerth's user avatar
  • 42
0 votes
1 answer
101 views

Thread blocking even when LinkedBlockingQueue is empty

For clear investigation I have only one thread producing an entity and one thread consuming it. These two parts share LinkedBlockingQueue. After consuming the entity the thread pass it forward to ...
ordinary user's user avatar
1 vote
2 answers
445 views

Why calling notify in Java requires holding the lock?

Thread thread = new Thread(() -> { synchronized (this){ try { this.wait(); System.out.println("Woke"); } catch (InterruptedException e) { ...
Name Null's user avatar
  • 400
0 votes
0 answers
60 views

Should I guard Map.clear() with readLock or writeLock of j.u.c.l.ReentrantReadWriteLock

In my code I'm using ReentrantReadWriteLock to guard some paired read/write operations: public class AgreementCache { private final ConcurrentMap<String, Agreement> agreements = new ...
Sergey Tsypanov's user avatar
1 vote
1 answer
107 views

How to use CompletableFuture to execute the threads parallaly without waiting and combine the result?

I have executeGetCapability method which is executed in different threads but these threads runs sequentially..meaning one is completed after the other @Async("threadPoolCapabilitiesExecutor&...
MiGo's user avatar
  • 603
1 vote
1 answer
504 views

Striped ReadWriteLock throwing IllegalMonitorStateException - Attempt to unlock read lock, not locked by current thread

We are writing a concurrent multimap to store multiple values for the same key in a multi threaded application. We have extended Guava ForwardingMultimap to do the same. Put and remove methods acquire ...
arunK's user avatar
  • 398
1 vote
1 answer
83 views

CompletableFuture controlled way abort on exception

Let's suppose I have a CompletableFuture with a couple of stages chained: processedFuture = someCompletableFuture .thenApply(<stage1>) .thenApply(<stage2>) And let's assume that ...
frblazquez's user avatar
0 votes
1 answer
45 views

Concurrency constructs for processing shared list and posting results

There is a class as follows: class Foo { private int len; public Foo(int l) { this.N = N; } public void process(List<Bar> list) { int start = 0; while(start < list.size()) { ...
Jim's user avatar
  • 3,949
-1 votes
1 answer
56 views

set<int, Future<Integer> is not applicable to arguments (int,int)

Hi I am doing a concurrent programming task in java where I'm using an executorService consisting of 10 threads. I have an array containing 100 elements all set initially to 1000. What I am trying to ...
sufocator's user avatar
0 votes
1 answer
92 views

How can i return Future<T> using returns method in Bytebuddy?

I am intercepting a method which returns Future where i know that ‘T’ is subclass of ‘E’. How can i use returns() method of net.bytebuddy.matcher.ElementMatchers to achieve that. I want something like ...
Dr Drake Ramoray's user avatar
0 votes
1 answer
531 views

Implementing a multi-threaded web crawler with Java's ReadWriteLocks

I am trying to implement a multi-threaded web crawler using ReadWriteLocks. I have a Callable calling an API to get page URLs and crawl them when they are not present in the Seen URLs Set. From the ...
Karthik Kolathumani's user avatar

1
2 3 4 5
28