1,435 questions
2
votes
1
answer
65
views
ConcurrentMap: atomically check if a value if present, and then mutate it with a consumer
Given a Java ConcurrentMap, I would like to atomically:
Check if an entry is contained in the map
If it is present, run an action (I'm thinkng of a BiConsumer taking the key and its value)
Otherwise, ...
3
votes
1
answer
69
views
Is it possible in Java for a task scheduled with scheduleAtFixedRate to start executing before the returned ScheduledFuture has been assigned?
In Java, when using scheduleAtFixedRate, is it possible for a task to execute before the ScheduledFuture returned by scheduleAtFixedRate has been assigned?
For example, could the following code throw ...
2
votes
1
answer
135
views
Does the JNI provide direct access to _Atomic values for the respective Java Atomic classes?
When working with JNI, can the native side obtain an _Atomic int32_t* given a Java AtomicInteger reference, and run C atomic functions on it (e.g. atomic_fetch_add)?
We could call Java's methods (e.g. ...
2
votes
1
answer
87
views
Can thread-unsafe combiner be used in Stream.collect method in java 8?
For a parallel Stream, the collect method has a 3-arg variant: (source: oracle documentation )
/**
Parameters:
supplier - a function that creates a new result container. For a parallel execution, this ...
2
votes
0
answers
110
views
Long term behavior of ScheduledExecutorService.scheduleAtFixedRate when tasks run too long
I'm using java.util.concurrent.ScheduledExcecutorService.scheduleAtFixedRate to execute a task periodically. I run it once every minute and it usually completes after 5 seconds, but occasionally runs ...
0
votes
1
answer
117
views
Concurrent & Thread issues
I have a multithreaded program that both produces output via a timer and receives user input. It behaves badly when I want to type in a command such as "pause" or "stop": anything ...
3
votes
1
answer
87
views
Can not reproduce experiment about RA mode of J9mm
I attempted to replicate the experiment about "Release/acquire" from Doug Lea‘s blog on j9mm (https://gee.cs.oswego.edu/dl/html/j9mm.html#summarysec) :
volatile int ready; // Initially 0, ...
0
votes
0
answers
33
views
modify java protobuf and protobuf extensions in parallel, version > 3.17
I have generated java protobuf class. This class has protobuf extensions also. Is it safe to modify different unrelated fields and extensions of the same protobuf builder in parallel?
message ...
4
votes
1
answer
213
views
thenCompose hangs/timeout web graphql application
Im trying to create a Java App using SpringBoot 3 framework and GraphQL. I'm trying to resolve a field which depends on several dataLoaders within my App however, I seem to be running into an issue ...
-1
votes
1
answer
58
views
Method Breaks After Implementing Focus Switching
I'm currently working on a concurrent implementation of multiplayer Tetris in JavaFX where each game is run on a separate Stage. Each game has its own set of inputs so you can play simultaneously as ...
0
votes
1
answer
78
views
Is there a way to switch the focus window upon a key press in JavaFX
Edit: I've cut down Mainboard to just the relevant function to make code shorter to read. If any additional code needs to be read to help understanding, please say
I'm currently making a multiplayer ...
0
votes
1
answer
107
views
Attach finally logic to CompletableFuture [duplicate]
I need to asynchronously consume future value and then run logic X. In case of any exceptions, I also want to execute logic X. In a way, it is semantically akin to the finally block.
I do not have a ...
-4
votes
1
answer
177
views
How to safely reset AtomicInteger value in highly multithreaded environment? [closed]
The class implementation below wraps two AtomicInteger fields. After the max=9999 value is reached, the main sequence number is expected to reset to zero. When the sequence number resets, the ...
1
vote
2
answers
109
views
Forking exception handling in Java CompletableStage
I have not used Java in a million years and trying to figure out how to differentiate between different types of Exception in CompleteableStage.
Currently, I have something like below but it does not ...
0
votes
3
answers
146
views
Spring 6.2 DefaultManagedTaskExecutor throws java.lang.UnsupportedOperationException: isShutdown when rejecting tasks
I have a problem regarding spring DefaultManagedTaskExecutor. We are deploying our SpringBoot 3.2.5 application to websphere Liberty and we are using Liberty ManagedExecutorService as external ...
2
votes
1
answer
534
views
Can't reproduce virtual thread pinning (jdk 21), yet mysql not as parallel as should be
The jdk 21 doc about virtual threads (hereafter "VT")
(https://docs.oracle.com/en/java/javase/21/core/virtual-threads.html)
is pretty clear about a synchronized block causing a thread to be ...
0
votes
1
answer
25
views
afterExecute method is not invoked defined in CustomThreadPoolExecutor that is passed to RabbitMQ Spring SimpleRabbitListenerContainerFactory
Spring-Rabbitmq SimpleRabbitListenerContainerFactory is defined with a CustomThreadPoolExecutor.
@Bean
public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(final ...
1
vote
0
answers
205
views
Queued Thread Pool High CPU Usage
I have a Java process consuming upwards of 400% CPU on my server (AlmaLinux) which shouldn’t be the case.
On my analysis I find multiple QTPs (Queued Thread Pools) consuming the CPU:
After analysing ...
1
vote
2
answers
194
views
How to interact with concurrent collections from Kotlin?
From the library I use I get ConcurrentMap. I want to obtain it's keys as Set.
How to do it in thread-safe way (since Kotlin collections API is thread-unsafe)?
0
votes
2
answers
121
views
Missed signal in a Java
Can this code ever lead to missed signal? If yes, then how?
private Object lock = new Object();
private boolean conditionMet = false;
public void waitForCondition() throws InterruptedException {
...
0
votes
0
answers
96
views
Java 21 Create StructuredTaskScope from ExecutorService
Fine, this is most probably a silly question...
Is there a way to construct a StructuredTaskScope using an ExecutorService?
Any idea is welcome.
Best regards
Alex
0
votes
2
answers
52
views
load test in jmeter is generating duplicate consecutive IDs using multiple threads
Scenario
I am creating some records in a system using three requests of its API. In the first request I need to send and Id which for testing and tracking purposes I am using a consecutive number ...
1
vote
0
answers
62
views
Concurrent round robin implementation fails
I'm trying to write an in-memory implementation of the load balancer that will have a get() method returning the instances in a round-robin pattern, I need it to run properly in a concurrent ...
2
votes
0
answers
75
views
Java ThreadPoolExecutor: How can it ensure the state check in execute() method is safe?
Basic:
// this.a is a shared variable.
AtomicInteger a = this.a;
int x = a.get();
In a multi-threaded condition, we cannot ensure that x is 1 because some other thread may call something like a....
-1
votes
2
answers
236
views
Conditionally set AtomicReference
I would like to conditionally and atomically update (or set if the current is empty) an AtomicReference based on a Predicate on the current value.
I was hoping that something like this existed:
/**
* ...
1
vote
1
answer
123
views
Java concurrency problem by multi-thread not occured and automatically synchronized
I’m trying to test a multi-threaded concurrency problem.
What I expected is that the result should be less than 0 (not always but sometimes), because it is not synchronized.
Notice the pair of println ...
0
votes
1
answer
117
views
Unit test CompletableFuture exceptions
It's my first post and I'm a beginner with CompletableFuture and I want to test exceptions (InterruptedException and TimeoutException) when I use CompletableFuture.get().
My code:
CompletableFuture<...
1
vote
2
answers
2k
views
Java 17 Fork join pool limit number of threads in pool
In java 17, we are seeing that a lot more threads are getting created (although not concurrently executing) as compared to older java version (java 8 in my case). While thread itself may not be a huge ...
1
vote
1
answer
69
views
Is CompletableFuture.supplyAsync() redundant in case it does not modify the incoming value?
During a course on concurrent programming, I've run into this sample code:
@Test
void promiseTestCompose2() throws Exception {
CompletableFuture<Integer> future1 = CompletableFuture
....
0
votes
2
answers
685
views
Understanding Java concurrency [closed]
I'm learning java concurrency under the hood and I've read some java article and videos regarding multi threading and concurrency and just can't seem to put them all together
Here is the gist of what ...
0
votes
0
answers
41
views
Does CopyOnWriteArrayList can result inRace Condition when modified by 2 or more Threads in Parallel
I was trying to do some experminet with CopyOnWriteArrayList and found that when 2 threads are concurrently modifying same CopyOnWriteArrayList object, the final result changes in different run.
...
0
votes
0
answers
47
views
Java async serial port communication request response
I am trying to create a class which sends and receives commands via serial port. Sadly the whenComplete is never called. I also tried to log the response and in the callback it is correct but when I ...
1
vote
1
answer
193
views
Why calling take() method Java DelayQueue doesn't block the whole data structure for all threads?
I'm trying to figure out, how the java.util.concurrent.DelayQueue works in the multithreaded environment. I see that this data structure uses ReentrantLock internally, and it is acquired at the ...
-4
votes
1
answer
93
views
LeetCode 1116 Java Concurrency Issue, will waiting thread revisit code before? [closed]
Here is my code for the problem which works fine, however, when I change the while statement right under synchronized statement, it seems any thread that get the lock after notifyall() just continue ...
1
vote
1
answer
167
views
Issues with Concurrent Execution and Synchronization in a Custom Java Caching Mechanism
I’m developing a custom caching mechanism for my Java application to cache objects that are expensive to create (e.g., database connections). The idea is to allow concurrent access to the cache while ...
-1
votes
1
answer
233
views
How does completablefuture works? [closed]
Need to know the insights of the complete future task without an executor.
Here is my sample code
CompletableFuture.runAsync(() -> {
dosomething();
});
How is this task assigned to the thread? ...
2
votes
1
answer
1k
views
TraceId and Span are empty in async task logs
I have a REST endpoint in springboot which calls an external api async multiple using CompleteableFuture. The external api is called using resttemplate in Completeablefuture.supplyAsync(() => ...
0
votes
0
answers
310
views
CompletableFuture - Exception Cause / Stack trace not available
I have an async application. By executing for example the async method getTest() I never get the full strack trace caused the error:
CompletableFuture<Test> test = myAdapter.getTest();
test....
0
votes
0
answers
38
views
Data loss when adding a record to the database
Help me understand the work with the database, on the 3-5 iteration, data is incorrectly written to the database in the lemma table, the site is correctly recorded, the page is also, but when lemma ...
-2
votes
1
answer
120
views
Only one of my threads executes when trying to use a Semaphore [closed]
To my understanding, java.util.concurrent.Semaphore allows me to specify how many threads can use a resource at once. A thread can use Semaphore.acquireUninterruptibly() to consume the limited number ...
-1
votes
1
answer
1k
views
Why executor service submitted task is not executing the task async?
I'm trying to play with async java in my intellij local. My intention is that i will call calucalateAsync() method from main method and then put the debug point on System.out.println("calculate ...
17
votes
1
answer
30k
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 ...
0
votes
1
answer
76
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 <...
0
votes
0
answers
43
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 ...
0
votes
2
answers
369
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 ...
-2
votes
1
answer
38
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;...
0
votes
1
answer
127
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 {
...
0
votes
1
answer
71
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 ...
3
votes
1
answer
146
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 ...
0
votes
1
answer
131
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 :
/
**
* ...