FAQ Database Discussion Community


ThreadPoolExecutor application does not Finish

java,concurrency,threadpool,threadpoolexecutor
This super simple application prints "Hello" but does not finish. I see absolutely no reason why this should be. JavaDoc, section finalization, says that A pool that is no longer referenced in a program AND has no remaining threads will be shutdown automatically. tpe is clearly not referenced, that means...

Correct use of go context.Context

concurrency,go,gorilla
I just read the article: Build You Own Web Framework In Go and for sharing values among handlers I picked the context.Context and I'm using it in the following way to share values across handlers and middlewares: type appContext struct { db *sql.DB ctx context.Context cancel context.CancelFunc } func (c...

Moving Arc Mutex Ncurses window down thread still doesn't implement send

concurrency,rust,ncurses
I'm building an ncurses interface for a little thing I'm working on. For the input, I want to read it non blocking. I figured I could wrap the WINDOW in an Arc Mutex but this doesn't seem to work, as it still complains about send. Is this because the implementation...

Clojure invokeLater null pointer

swing,concurrency,clojure
This code: (import 'javax.swing.SwingUtilities) (SwingUtilities/invokeLater (print "hi")) Causes this error: Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209) ... I don't know if this is a problem, since the code itself actually works (printing to the REPL) despite the error. However, modifying swing components does not seem to work properly: a...

For producer-consumer pattern which implementation is better : ArrayBlockingQueue or Arraylists with Exchangers

java,concurrency,producer-consumer
Usecase : its a producer consumer pattern where order (FIFO) is to be maintained. As of now there is single producer and a single consumer to process data in sequential manner to maintain order, but in future ( due to removal of some business constraint ) this requirement of maintaining...

erlang processes and message passing architecture

concurrency,process,erlang,messages
The task I have in hand is to read the lines of large file, process them, and return ordered results. My algorithm is: start with master process that will evaluate the workload (written in the first line of the file) spawn worker processes: each worker will read part of the...

Running java application parallely on multicore cluster nodes

java,multithreading,concurrency,parallel-processing
I have a Java program that calculates semantic similarity between two documents. The program retrieves documents from a specified file system and calculates similarity. There are around 2,00,000 such docs. I have created 10 threads for this task and I have assigned data chucks to each of the thread. For...

Nested synchronized block

java,multithreading,concurrency,synchronized
Let's imagine I have next classes: public class Service { public void transferMoney(Account fromAcct, Account toAcct, int amount) { synchronized (fromAcct) { synchronized (toAccount) { // could we use here only one synchronized block? fromAcct.credit(amount); toAccount.debit(amount); } } } } class Account { private int amount = 0; public void...

Do concurrency issues in kernel happen when using single core processor?

concurrency,linux-kernel,multicore
When a kernel is compiled on a multicore system, there will be multiple threads or processes operating simultaneously. So, concurrency problem will be an issue. However, when there is only one core in the processor. will it still be a problem?...

producer / hybrid consumer in C# using 4.0 framework classes and Blocking Collection

c#,multithreading,c#-4.0,concurrency,producer-consumer
I have a situation in which I have a producer/consumer scenario. The producer never stops, which means that even if there is a time where there are no items in the BC, further items can be added later. Moving from .NET Framework 3.5 to 4.0, I decided to use a...

JPA difference between transaction isolation and entity locking

java,database,jpa,concurrency,transactions
I have read about transaction isolation levels. It is used to prevent parallel transaction executions errors. Its quite obvious. There are also locking modes available for entities. I understand how they work. But I cant find the reason why I need locking? I have used transaction isolation levels already. Why...

Higher priority thread getting the same CPU amount as the lower priority?

java,multithreading,concurrency,thread-priority
Following is my code. public class Test { public static void main(String[] args) throws InterruptedException { PrintingThread a = new PrintingThread("A"); a.setPriority(9); PrintingThread b = new PrintingThread("B"); b.setPriority(1); a.start(); b.start(); } static class PrintingThread extends Thread { private int i = 0; private String name; public PrintingThread(String name) { super();...

Custom Future objects

java,multithreading,concurrency,threadpool
I'd like to create custom Future objects. The following code works fine ThreadPoolExecutor mExecutor; Future<?> f = mExecutor.submit(new DownloadRunnable(task, itemId)); I'd like to take the return value of submit and assign it to MyFuture object, with additional calls. I've made the following changes, and getting a cast exception... Any suggestions?...

Unable to get CallableThread in RejectionHandler

java,multithreading,concurrency
I have thread pool, which will take Callable worker thread with a RejectionHandler. I need to get this Callable task in RejectionHandler but unable to get it. In this below example, I need uniqueId of Callable task for which RejectionHandler executed. In RejecitonHandler, the Runnable is casted FutureTask where I...

Use DEFAULT or INTEGER value as a SQL function's argument

sql,postgresql,function,concurrency,sql-insert
I am making a SQL function to perform a smart insertion and manage a many to many table (a trigger wouldn't work as one value is variable). Here is a minimum set for the example: link_foo_to_bar (foo_id int, bar_id int) foo (id serial, name character varying) And here's my sql...

goroutine blocks when calling RWMutex RLock twice after an RWMutex Unlock

concurrency,go,mutex
var mu sync.RWMutex go func() { mu.RLock() defer mu.RUnlock() mu.RLock() // In my real scenario this second lock happened in a nested function. defer mu.RUnlock() // More code. }() mu.Lock() mu.Unlock() // The goroutine above still hangs. If a function read-locks a read/write mutex twice, while another function write-locks and...

Using Java multithreading, what is the most efficient to coordinate finding the best result?

java,multithreading,concurrency,java-8
Let me be clear, the method I describe below is operational. I'm hoping to improve the throughput of the method. It works, and it works quite well. We're looking to scale throughput even more which is why I'm looking into this. The task at hand is to improve the performance...

how to convert java Future to guava ListenableFuture

java,concurrency,guava,futuretask
I need to find a way to convert from Future to ListenableFuture. Currently i'm using a service which returns Future but i need to hook up a listener to it. I can't change the service interface as it doesn't belong to me. Is there a simple way to do that...

When using a database that is supposedly thread-safe, do I need to synchronize my own threads?

python,multithreading,concurrency,nosql,rethinkdb
I'm writing a Python application that uses a Rethink database. I have three worker threads that need to run and possibly access the database at the same time. I know how to synchronize threads in Python, but my question is: do I need to? If Rethink claims to be thread-safe,...

Unicorn+Nginx concurrency and data duplication

ruby-on-rails,ruby-on-rails-3,nginx,concurrency,unicorn
I have 4 Nginx workers and 4 unicorn workers. We hit a concurrency issue in some of our models that validate unique names. We are getting duplicated names when we send multiple requests at the same time on the same resource. For instance if we send around 10 requests to...

Synchronous multithreading in Java (Apache HTTPClient)

java,multithreading,apache,concurrency,synchronizing
I am wondering how I would go about doing this. Say I load a list of 1,000 words and for each word a thread is created and say it does a google search on each word. The problem here is obvious. I can't have 1k threads, can I. Keep in...

Basic Java threading (4 threads) slower than non-threading

java,multithreading,concurrency,parallel-processing
I have a four core CPU. I create 4 threads and run a cpu intensive loop, and it takes > 4x longer than running it all procedurally in one thread. I created two projects to compare, one with threading and one without. I'll show the code and run times. Just...

Why JUnit using CountDownLatch to implement FailOnTimeout

java,junit,concurrency
I just started to read code of JUnit 4.13 (https://github.com/junit-team/junit), and get a little confused about the implementation of org.junit.internal.runners.statements.FailOnTimeout: @Override public void evaluate() throws Throwable { CallableStatement callable = new CallableStatement(); FutureTask<Throwable> task = new FutureTask<Throwable>(callable); ThreadGroup threadGroup = new ThreadGroup("FailOnTimeoutGroup"); Thread thread = new Thread(threadGroup, task, "Time-limited test");...

java, when (and for how long) can a thread cache the value of a non-volatile variable?

java,concurrency
From this post: http://www.javamex.com/tutorials/synchronization_volatile_typical_use.shtml public class StoppableTask extends Thread { private volatile boolean pleaseStop; public void run() { while (!pleaseStop) { // do some stuff... } } public void tellMeToStop() { pleaseStop = true; } } If the variable were not declared volatile (and without other synchronization), then it would...

Hibernate Query cache invalidation

java,hibernate,jpa,caching,concurrency
I am using Hibernate(with JPA) in an application that has a high write-read ratio. For caching I have enabled query-cache and hibernate second level cache(ehcache). The problem I am facing is due to automatic query cache invalidation when an update is done. Is there any way to configure query cache...

How LongAdder performs better than AtomicLong

java,concurrency
I see how Java's AtomicInteger works internally with CAS (Compare And Swap) operation. Basically when multiple threads try to update the value, JVM internally use the underlying CAS mechanism and try to update the value. If the update fails, then try again with the new value but never blocks. In...

Java - multithreading increment

java,multithreading,concurrency,synchronization
I have the following class in my application public class InsertErrorLinesHandler { private int currentCount; public void insertErrorLine() { //do something... currentCount++; } } And I have multiple threads that are using the same instance of InsertErrorLinesHandler, particulary calling insertErrorLine method. After all these threads are stopped, I get the...

concurrent http request to independent web services

java,concurrency
i'm trying to find a simple way to send http request concurrently to diferent web services. each request is completely independent of each other. currently, my implementation look like this ( just a simplification, don't pay attention to design ) let's say a i have a List queries; public class...

Executing more than 1000 HTTP request tasks fails

c#,concurrency,task-parallel-library,httprequest,task
I'm trying to load test an API. I'm executing a tasks at the same time, each executing an HTTP request. I use Task.WhenAll(mytasks) for waiting for all tasks to be finished. The requests look as follows: using (var response = await client.SendAsync(request).ConfigureAwait(false)) { using (var jsonResponse = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) {...

Why do I get random errors by using celluloid?

ruby,concurrency,celluloid
I need to make API calls to a webservice in order to retrieve date. For this purpose I created a sample in order to get familiar with celluloid. Here I ll user the openweather API for "training" purpose. The ultimate goal is to run multiple requests in concurrently. my booking...

Usage of lazySet on AtomicXXX in Java

java,concurrency,java.util.concurrent
From this question : AtomicInteger lazySet vs. set and form this link : https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/package-summary.html I could gather following points lazySet could be faster than set lazySet uses store-store barrier (writes before are honored but not the contended writes, which were yet to happen) I could find one use-case where it...

Java combine explicit locks with synchronized methods

java,multithreading,concurrency,synchronization,locking
I have a thread safe class Container: public class Container { private int x; ... public synchronized int getX(); public synchronized void setX(int x); } Then I have a list of containers: List<Container> containers; I would like to iterate through the list, aquire the container's lock at each iteration and,...

Unable to lock file using flock with file descriptor

linux,shell,concurrency,locking
First let me show what works. If I use flock with the file path, it works. Terminal 1: [[email protected] ~]# flock -x -n /tmp/foo.txt -c "sleep 100" Terminal 2: [[email protected] ~]# flock -x -n /tmp/foo.txt -c "sleep 100" [[email protected] ~]# echo $? 1 The above output shows that I first...

Concurrent programming - Is it necessary to manually lock files that multiple processes will be accessing?

c,concurrency,process,fork
I know for pthreads, if they're modifying the same variables or files, you can use pthread_mutex_lock to prevent simultaneous writes. If I'm using fork() to have multiple processes, which are editing the same file, how can I make sure they're not writing simultaneously to that file? Ideally I'd like to...

Are JavaFX Property objects threadsafe for multiple asynchronous writes?

java,multithreading,concurrency,javafx,javafx-8
Is it dangerous for the standard implementations of Property in JavaFX to call set methods from multiple threads? I don't really care about race conditions on the client side from reading-and-then-setting operations. I want to know if the Property itself can be corrupted internally if multiple threads call its set()...

Scala parallel frequency calculation using aggregate doesn't work

multithreading,scala,concurrency,parallel-processing,aggregate
I'm learning Scala by working the exercises from the book "Scala for the Impatient". Please see the following question and my answer and code. I'd like to know if my answer is correct. Also the code doesn't work (all frequencies are 1). Where's the bug? Q10: Harry Hacker reads a...

Can thread be used analogously with queue, or do they mean separate things?

objective-c,multithreading,swift,concurrency,grand-central-dispatch
I was reading through this great tutorial when I came accross the following line (as background: we were learning how to use dispatch_apply to replace a for loop and concurrently download photos): Be aware that although you have code that will add the photos in a thread safe manner, the...

Concurrency of JPA when same DB used by other applications

java,spring,jpa,concurrency
I am developing a Spring MVC JPA web application. When this application is deployed in live the same DB that my application interacts with will be used by other 2 Dotnet and VB applications at the same time. I am managing the concurrency of my JPA app through version column....

monitor log4j behaviour under load

logging,concurrency,io,log4j
I want to test my J2EE application under high load of sessions accessing different pages. This web application uses Log4J to log bunch of errors,warnings and infos. I want to test what is the side effect of this load on writing log files, especially concurrent I/O writing actions. I found...

Why this indeterminate jProgressBar don't work in this simple code?

java,swing,concurrency,process,jprogressbar
I want use an indeterminate jProgressBar on a JForm but I don't know why in my code don't work. The jProgressBar must be in the indeterminate status until the thread receives a latch.await() signal. This is the simple part of code when I push a button: private void jButton5ActionPerformed(java.awt.event.ActionEvent evt)...

Why i used synchronized list and still get ConcurrentModificationException [duplicate]

java,android,concurrency,thread-safety
This question already has an answer here: Why does one loop throw a ConcurrentModificationException, while the other doesn't? 5 answers I have found a same question in I used synchronized list, and i still get ConcurrentModificationException, but i didn't find a correct answer. Here is how i defined my...

Whats the best way to asynchronously return a result (as a struct) that hasn't been fully “set up” (or processed) yet

c,asynchronous,concurrency,pthreads,threadpool
Alright, I honestly have tried looking up "Asynchronous Functions in C" (Results are for C# exclusively), but I get nothing for C. So I'm going to ask it here, but if there are better, already asked questions on StackExchange or what-have-you, please direct me to them. So I'm teaching myself...

How does asyncio (python) work?

python,concurrency,parallel-processing,python-asyncio
Yield from coroutine vs yield from task As reported in this question(second answer) "yield from coroutine()" is like calling a function. I don't understand how something like yield from, that actually waits until the coroutine is finished should enable concurrency and non blocking operations. For example in Golang you just...

Use of serialized target queues for Concurrent queues in iOS

ios,concurrency,queue
I was going through this excellent blog post (http://www.humancode.us/2014/08/14/target-queues.html) of target threads in iOS and I could not help but wonder why do we need such a mechanism. In the example, we are specifying a serialised target queue for a custom concurrent queue. Can we not achieve the same by...

sync.WaitGroup doesnt waits

concurrency,go
May be I can not see obvious thing, what am I doing wrong: func printSize (listOfUrls []string){ var wg sync.WaitGroup wg.Add(len(listOfUrl)) for _, myurl := range(listOfUrls){ go func(){ body := getUrlBody(myurl) fmt.Println(len(body)) wg.Done() }() } wg.Wait() } If I remove wg and go, I receive the size of each url...

Would this fill the child context with only TemporaryIDs?

ios,objective-c,core-data,concurrency
I was wondering if someone would be able to answer this question. I am currently building my application using the CoreData stack as described by Marcus Zarra in his blog http://martiancraft.com/blog/2015/03/core-data-stack/. He describes the usage of managedObjectContext as the Single Source Of Truth where all insertions/updates/deletions should be done on...

Python thread pools - tasks that create subtasks and wait on them

python,multithreading,concurrency,threadpool,concurrent.futures
Say I have a thread pool executor with max. 10 threads, and I submit a task to it which itself creates another task and in turn waits for it to complete, recursively until I reach a depth of 11. Example code in Python: import concurrent.futures e = concurrent.futures.ThreadPoolExecutor(max_workers=10) def task(depth):...

Am I approaching concurrency right?

ios,objective-c,core-data,concurrency
I was wondering if someone could point me in the right direction about whether or not I am using concurrency correctly. I find that currently, the code is very unwieldy and almost unintuitive. For the purposes of my demonstration, please note the CoreData architecture is as described by Marcus Zarra...

What does it mean when one language is a parallel superset of another?

c++,c,concurrency,programming-languages,real-time
I'm reading a journal article about Real-Time Concurrent C, and it mentions in the abstract (so any of you can see the context through that link as well) that "Concurrent C, is a parallel superset of C (and of C++)". Now I know what a superset is, but what do...

Copying in Vectors to a Thread

multithreading,concurrency,rust
Considering the following code, I wish to have access to both client and requests within my thread, currently I do not: for _x in 0..100 { let handle = thread::spawn(move || { let start = time::precise_time_s(); let res = client.get("http://jacob.uk.com") .header(Connection::close()) .send().unwrap(); let end = time::precise_time_s(); requests.push(Request::new(end-start)); }); handle.join().unwrap() }...

Produce Consumer

java,multithreading,concurrency
I tried to implement Producer Consumer pattern with wait() and notifyAll() methods, but have some issues. So my code is next. Main class: import java.util.LinkedList; import java.util.List; public class TestThread { public static void main(String[] args) { final List testQueue = new LinkedList(); final Producer producer = new Producer(testQueue); final...

Entity Framework Code First with Fluent API Concurrency `DbUpdateConcurrencyException` Not Raising

c#,asp.net,asp.net-mvc,entity-framework,concurrency
I am trying to handle concurrency using entity framework 6. My entity looks like below; public partial class Group : BaseEntity { public byte[] RowVersion { get; set; } ............... } Mapping public partial class GroupMap : EntityTypeConfiguration<Group> { public GroupMap() { this.ToTable("CRM_Sales_Group"); this.HasKey(c => c.Id); //tried like this too...

Make HTTP request inside Web Worker

javascript,node.js,multithreading,concurrency,web-worker
I am trying to use web-workers or threads in my node application for the first time. I am using the webworker-threads npm module. Basically I would like each worker to make requests to a server, measure the response time and send it back to the main thread. I tried it...

What is the recommended way to wait till the Completable future threads finish

java,multithreading,concurrency,completable-future
I am using CompletableFuture as shown below in the code. but concerning the way i should wait till all runnables finish, i found two ways and i do not know the difference between them and which one is the best practice? they are as follows: code: this.growSeedFutureList = CompletableFuture.runAsync(new GrowSeedSERun(this.saliencyMat,...

SQlite WAL-mode in python. Concurrency with one writer and one reader

python,sqlite,concurrency
I'm trying to share a sqlite3 database between one writer process, and one reader process. However, it does not work, and it seems to me that nothing is being written in example.db. reader.py import sqlite3 from time import sleep conn = sqlite3.connect('example.db', isolation_level=None) c = conn.cursor() while True: c.execute("SELECT *...

Is it possible to have a set of thread pools that share threads from a large thread pool instead of creating new thread?

java,multithreading,concurrency,threadpool,executorservice
Is it possible to have a set of thread pools that share threads from a large thread pool instead of creating new thread? In our RESTful API application, a request may involve several parallel tasks. To improve the performance, we want to execute parallel tasks in a thread pool which...

Can operations, which assign values to multiple volatile fields consecutively, be reordered?

java,concurrency,thread-safety,volatile,java-memory-model
Will the following code always print-out the "correct" value of data? Even if there are other operations between assigning the values to data and dataReady in method setData? Or could the JVM conceivably re-order these operations such that RunningThread could see dataReady as true whilst data were still null? If...

Jersey Client, memory leak, static and concurrency

java,concurrency,jersey,jersey-2.0,jersey-client
I am using Jersey Client (v2.17) to make external calls from my app. I found out this memory leak bug (the CPU consumption was very high) which made me re-write my code to make the client static like this: public class GeneralUtil { private static final Client client = ClientBuilder.newClient()...

Is using own int capacity faster than using .length field of an array?

java,performance,caching,concurrency
In the "95% of performance is about clean representative models" talk by Martin Thompson, between 17 and 21 minute, such code is presented: public class Queue { private final Object[] buffer; private final int capacity; // Rest of the code } In 20:16 he says: You can get much better...

Using a shared queue that workers can add tasks to

python,concurrency,multiprocessing,python-multiprocessing
I'm pretty new to python (I mainly write code in Java). I have a python script that's essentially a crawler. It calls phantomjs, which loads up the page, returns its source, and a list of urls that it found in the page. I've been trying to use Python 3's multiprocessing...

is javascript a concurrent language or is it the javascript engines that makes the language concurrent?

javascript,concurrency
Is it correct to say that javascript is a concurrent programming language or is it rather the different javascript engines that makes javascript concurrent? Javascript as a concurrent language is not listed on wikipedia, but node.js is: http://en.wikipedia.org/wiki/Concurrent_computing#Concurrent_programming_languages. I would appreciate some more information about where the concurrent behaviour of...

ConcurrentBag vs Custom Thread Safe List

c#,multithreading,concurrency,.net-4.5,readerwriterlockslim
I have a .NET 4.5 Single Instance WCF service which maintains a collection of items in a list which will have simultaneous concurrent readers and writers, but with far more readers than writers. I am currently deciding on whether to use the BCL ConcurrentBag<T> or use my own custom generic...

When a ConcurrencyException occurs, what gets written?

concurrency,ravendb
We use RavenDB in our production environment. It stores millions of documents, and gets updated pretty much constantly during the day. We have two boxes load-balanced using a round-robin strategy which replicate to one another. Every week or so, we get a ConcurrencyException from Raven. I understand that this basically...

Breakpoint “concurrency” in Intellij

java,debugging,intellij-idea,concurrency,ide
Lets say I have a class that initiates two threads Thread_A and Thread_B, each doing some calculations and ocassionally using a subroutine of my the class. (don't worry about data sharing, lets say it's a log line or imagine the subroutine is a method in a Java library) I want...

Ensure atomicity when saving a model

python,django,database,concurrency,atomic
I am quite new to Django, and I am not sure how to manage concurrency. I am building an application to reserve equipments. I have a Reservation model with a ManytomanyField of Equipments. When I create a new reservation, I have to ensure that all the equipments are available. The...

How to introduce string by keyboard in child after fork

c,concurrency,process,signals,scanf
I'm exercising over concurrency in C, I wrote a small and simple program in which a parent process creates two children, sender and receiver. Sender will read from stdin a string and then procede to send it in some way to receiver (not relevant). The real problem here is that...

Why does my concurrent function exit prematurely in Go?

concurrency,go
I am looking through Go Bootcamp and am reading the Go Concurrency chapter right now. I have never used concurrency before in programming and don't understand the output of this program: package main import ( "fmt" "time" ) func say(s string) { for i := 0; i < 2; i++...

NServiceBus and concurrency

concurrency,nservicebus
This link talks about how NServiceBus handle concurrency for sagas. However, it does not show an example that explains when the concurrency can happen. In an e-commerce application, the orders are per user so there is not a case of multiple users updating the same order. I don't see a...

Thread blocked indefinitely in an MVar operation

haskell,concurrency,network-programming
I have been attempting to debug a problem when using multiple MVars, however to no luck. My code uses two MVars: one to store the servers current state, and another to pass network events to and from the client threads. However after connecting and disconnecting several times, the server stops...

What is preventing my event handler method from completing?

c#,wpf,concurrency,exception-handling,event-handling
I'm using a SerialPort, WPF for user interface, a 'ui' object to handle application logic, and a wrapper around SerialPort. The method in question is called when the SerialPort.DataReceived event is fired. It begins to run, then after reading the data, just seems to exit, even though it has tons...

Opening a file output stream on a file that is already locked overwrites it

java,concurrency,filelock
I came across this scenario and did not understand why it is happening. Can someone please help me understand the behaviour of nio file lock. I opened a file using FileOutputStream and after acquiring an exclusive lock using nio FileLock I wrote some data into the file. Did not release...

How do I atomically increment a variable in Swift?

swift,concurrency
I want to be able to increment a counter atomically and I can't find any reference on how to do it. Adding more information based on comments: Are you using GCD? No. I am not using GDC. Having to use a queue system to increment a number seems overkill. Do...

How to implement immutable cache in Scala?

scala,caching,concurrency,future
Suppose I have a server, which calls a time consuming function slow: Int => String upon a client request. If slow does not return within the timeout the server returns an error to the client. def trySlow(timeout: Duration)(id: Int): Try[String] = { val fut = Future(slow(id)) try { Await.ready(fut, timeout).value...

Future cancel method documentation

java,concurrency,documentation,future,java.util.concurrent
According to http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html isDone returns true if cancel(boolean mayInterruptIfRunning) was called. After this method returns, subsequent calls to isDone() will always return true. However, it is possible that task is running and mayInterruptIfRunning is set to false. So, what should return isDone() right after that call? true because of cancel...

Observing changes in a BlockingCollection without consuming

c#,multithreading,concurrency,producer-consumer,blockingcollection
A consumer thread and multiple producer threads synchronize their work with a System.Collections.Concurrent.BlockingCollection<T>. The producers call blockingCollection.Add() and the consumer runs foreach (var item in blockingCollection.GetConsumingEnumerable()) {...} Now one producer wants to "flush" the buffer: The producer wants to wait until all current items have been consumed. Other producers may...

Goroutines with ListenAndServe increases performance?

concurrency,go
I'm not very familiar with Go's routines but since I'm working with the router of net/http I saw a few times thatListenAndServe() is wrapped by a go routine. A server needs to be able to handle multiple requests simultaneously out of the box to be efficient. So why are go...

Set priority of thread groups in Microsoft PPL

multithreading,concurrency,scheduler,priority,ppl
I have a scenario where some functions need to complete as quickly as possible and be given computation resources at the expense of other tasks (i.e. they are high-priority). Specifically, graphics rendering and any tasks that are spawned for rendering should run as quickly as possible but do not consume...

Why are these tasks started in same thread?

c#,multithreading,concurrency
I am trying to understand threading better and I have run into something that is confusing me. As far as I know Task.Run() starts the task in another thread. I built some code below to test it out to see how it behaves but there is a hole in my...

Spin locked stack and memory barriers (C++)

c++,multithreading,c++11,concurrency,memory-barriers
I have a implementation spin lock: class Spinlock { public: void Lock() { while (true) { if (!_lock.test_and_set(std::memory_order_acquire)) { return; } } } void Unlock() { _lock.clear(std::memory_order_release); } private: std::atomic_flag _lock; }; I use SpinLock class in: class SpinlockedStack { public: SpinlockedStack() : _head(nullptr) { } ~SpinlockedStack() { while (_head...

What the difference between ExecutorService's execute and thread.run in running threads concurrently in Java?

java,multithreading,concurrency
I'm new to this concurrent programming in java and came up with following scenarios where I'm getting confusion which to use when. Scenario 1: In the following code I was trying to run threads by calling .start() on GPSService class which is a Runnable implementation. int clientNumber = 0; ServerSocket...

Java 8 parallelStream for concurrent Database / REST call

java,multithreading,concurrency,parallel-processing,java-8
Here I am using Javaparallel stream to iterate through a List and calling a REST call with each list element as input. I need to add all the results of the REST call to a collection for which I am using an ArrayList. The code given below is working fine...

Deadlock concurrency issue in C eventcounter + sequencer

c,concurrency
I'm trying to get this code to work, but for some reason it deadlocks within 30 seconds. The deadlock seems to happen Putting or Getting, whether the buffer is full not. Am I missing something obvious or not using something right? I'm new to C! To compile: gcc -Wall -o...

Java- Concurrency & Interleaving

java,multithreading,concurrency
So our task is to find an interleaving which results in a result < 10. Right now im having trouble finding said interleaving. My first idea was something like: -doing the for-loop from the first thread till the last iteration -then the threads start to interleave so sum gets reset...

Side effects not realized without deref

concurrency,clojure
From clojure for the brave and true: (defmacro enqueue [q concurrent-promise-name & work] (let [concurrent (butlast work) serialized (last work)] `(let [~concurrent-promise-name (promise)] (future (deliver ~concurrent-promise-name (do [email protected]))) (deref ~q) ~serialized ~concurrent-promise-name))) (defmacro wait "Sleep `timeout` seconds before evaluating body" [timeout & body] `(do (Thread/sleep ~timeout) [email protected])) (time @(-> (future...

Concurrent collection size calculation

java,multithreading,collections,concurrency
The documentation of most collections in the Java standard library such as ConcurrentLinkedQueue, ConcurrentLinkedDequeue and ConcurrentSkipListSet come with the following disclaimer: Beware that, unlike in most collections, the size method is not a constant-time operation. Because of the asynchronous nature of these sets, determining the current number of elements requires...

Lock+HasMap or ConcurrentHashMap in my case?

java,concurrency,thread-safety,java-7,concurrenthashmap
I have a Map<String, Queue<?>> and each time I have to put a couple (key, value) I need to get the not thread-safe Queue associated with that key and add a value to it (if key exist). Because I need to update an existing value (queue) I think that the...

Process a ConcurrentStack when not empty?

c#,multithreading,concurrency
I've got a ConcurrentStack that I'm dumping items into. What's a good way to process those items one at a time when the stack isn't empty? I'd like to do this in a way that isn't eating up CPU cycles when the stack isn't being processed. What I've currently got...

difference between locks and synchronized methods [duplicate]

java,methods,concurrency,synchronized,locks
This question already has an answer here: Synchronization vs Lock 6 answers I understand that synchronization allows for implicit locks, but don't these produce the same results? What is difference between the following two sections of code? Why would a programmer choose to use each? Code block #1 class...

Linux pthread Producers and Consumers

c,multithreading,concurrency,pthreads,producer-consumer
I have to write a POSIX threads and semaphores based implementation of Producers and Consumers Problem for academical purposes. To check if the implementation is valid I sum all the 'goods' which are produced and all which are consumed. The problem is that second sums vary between subsequent executions of...

In Scala, why is there no implementation for `Future.onComplete`?

scala,concurrency,akka,future
In the source code of Future module, I saw the definition of onComplete like this: /** When this future is completed, either through an exception, or a value, * apply the provided function. * * If the future has already been completed, * this will either be applied immediately or...

Sharing a mvar between threads

multithreading,haskell,concurrency
I'm trying to make a program that print arrows until the user press enter (see code bellow). The problem is that when I press enter, I see the "stop" string in the console, but it doesn't change the value of m in the outputArrows function. How can I share the...

Java 5 Multi threading, catch thread exceptions

java,multithreading,exception,concurrency,java-5
I've got a class that generates threads (file i/o). I need to catch exceptions in the thread - I don't want to do anything fancy, I want to kill the main thread, rather, stop processing altogether so it can start over. If I catch the exceptions in the thread, that's...

Compute in a new thread and refer to results later in R

r,concurrency,clojure
In clojure I can do something like this: (def x ;; perform some expensive computation in a new thread ;; the repl is not blocked, so you can go on do something else (future (do (Thread/sleep 500) 3.14))) ;; ... do something else ;; now when you need x ;;...

Scala Actors - any suggestions when converting OOP based approach?

scala,oop,concurrency,akka,actor
I'm learning Scala and its Actors (via Akka lib) approach for handling concurrency. I'm having some questions while trying to convert typical OOP (think - Java style OOP) scenarios to Actor based ones. Let's consider the overused e-commerce example Webstore where Customers are making Orders that contain Items. If it...

akka: pattern for combining messages from multiple children

scala,concurrency,mapreduce,akka
Here's the pattern I have come across: An actor A has multiple children C1, ..., Cn. On receiving a message, A sends it to each of its children, which each do some calculation on the message, and on completion send it back to A. A would then like to combine...

Why is asynchronous network testing difficult in Objective-C/Swift?

ios,swift,asynchronous,concurrency,grand-central-dispatch
So I'm learning more about how to test asynchronous code when I come across the following: As soon as a given test method completes, XCTest methods will consider a test to be finished and move onto the next test. That means that any asynchronous code from the previous test will...

ETag usage and resources modification

rest,concurrency,etag
Context I have 2 resources -it's an example, don't pay attention to the relevance of it- which are linked together: /customers/{id} that provide information about the age, sexe, firstName, etc... about a customer. /customers/{id}/age that corresponds to the age attribute of the customer. For performance issue, this resource exists. To...

nested asynchronous tasks (use CompletionStage in java)

java,concurrency
I use service (from library and i can't change it) that have 3 methods: CompletionStage<AData> getAData(int id); CompletionStage<BData> getBData(int id); CompletionStage<Path> computePath(int id); for my purpose i should get AData and BData, and then based on this values try compute some Path, and if i can't do it - use...

Using a condition instance with a lock

java,multithreading,concurrency,locking
What happens when a condition is associated with a lock like this: Lock lock = new ReentrantLock(); Condition notFull = lock.newCondition(); An example would be the bounded buffer class such as here So when, for example, the methods notFull.await() and notFull.signal() are called, what is being waited on to be...

Multiple NULL addition into a List in Java

java,list,concurrency,null,add
I have 2 lists and want to copy some element from one to another, i.e. there are old and new employees list I need to union 2 lists and delete the elements that include to the old list but not include in the new one. I could solve the part...