FAQ Database Discussion Community


unison issue on banana pi running lubuntu

ubuntu,synchronization,debian,unison
I am trying to two way sync my NAS (running lubuntu) from my local network to a remote server (running debian) with unison cli. I was using unison before syncing my laptops files directly with the remote server. I always get an issue when trying to sync files from my...

Java synchronization(object locking) not working as expected

java,multithreading,synchronization,thread-safety,thread-sleep
Please consider the below code. import static java.lang.System.out; public class Task { public Integer k = new Integer(10) ; public Task() { out.println(k + " constructor of Task : " + Thread.currentThread().getName()); } } import static java.lang.System.out; public class Executor2 implements Runnable { private Task task; public Executor2(Task t) {...

Synchronized DB Access in Java

java,mysql,multithreading,jdbc,synchronization
I have a database which contains e-mails to be sent. I'm using multiple threads to send out these e-mails. The approach I'm using is that each thread will query the database, get N e-mails in memory and mark those as being sent. Another thread will see those N e-mails as...

Javamail synchronization when opening mailbox, reading existing and starting MessageCountListener

java,synchronization,javamail
It seems to me there is no bullet-proof way to open an IMAP mailbox with Javamail, read the existing unread messages and add a MessageChangedListener event listener to read subsequent new arrivals. The app I am writing must process each message once only, and should never miss any emails. This...

I want to sync my local database with the one online [closed]

sql,database,sql-server-2008-r2,synchronization,replication
I want to sync my local database with the one online after a certain time I am using sql server Management 2008 r2 the purpose is to open reports online so that the client can check it from anywhere any suggestions to do this. I want to sync the local...

Is this code correctly synchronized?

c++,synchronization,stdasync
I wonder if this code is fine or not: #include <iostream> #include <future> struct Foo { Foo() :m_a(0) { } int m_a; }; int main() { Foo f; auto handle = std::async( std::launch::async, [](Foo* f) { std::cout << f->m_a << '\n'; } , &f ); handle.get(); } I believe m_a...

How to make function in loop run synchronously?

javascript,jquery,loops,google-chrome-extension,synchronization
Am working on a chrome plugin, and need to sendMessage from an 'app page' to a 'content script' and then get the return messages, from inside a loop. But since the loop doesn't wait for the sendMessage to return a value before starting on the next iteration, it is screwing...

How to compose thread safe operations and make them atomic?

java,multithreading,synchronization
Let's take a thread safe class like LinkedBlockingDeque: BlockingQueue<Task> taskQueue = new LinkedBlockingDeque<Task>(); I know that operations like take and put are thread safe, so they respect the happened-before relationship. But what if I want to compose some operations to make them atomic? Like this: if(taskQueue.size() == 1) { /*Do...

What is the purpose of passing parameter to synchronized block?

java,multithreading,synchronization,synchronized-block
I know that When you synchronize a block of code, you specify which object's lock you want to use as the lock, so you could, for example, use some third-party object as the lock for this piece of code. That gives you the ability to have more than one lock...

Can I call a synchronized method that calls a non-synchronized method that calls a synchronized method?

java,multithreading,synchronization,java-threads
In Java using the synchronized keyword all within a single object and thread. Can I call a synchronized method that calls a non-synchronized method that calls a synchronized method, without the final synchronized method blocking for the first synchronized method to be completed?...

No Synchronize Model with Database in Mysql Workbench

mysql,synchronization,schema,mysql-workbench,sync
I'd like to synchronize a model in Mysql workbench. However, I can't find the wizard following these steps in the docs. How do I enable this feature? I'm running 6.3.3.0 (latest) on Mac Os X . ...

Do I have to signal an anonymous thread to exit if the main thread is done? [duplicate]

multithreading,delphi,synchronization,delphi-xe2,terminate
This question already has an answer here: Is it necessary to explicitly stop all threads prior to exiting a Win32 application? 5 answers Suppose I have an anonymous thread that does some background processing: procedure TForm1.FormCreate(Sender: TObject); begin TThread.CreateAnonymousThread(procedure begin while True do begin Sleep(500); OutputDebugString('I am alive'); end;...

Synchronization on an instance in java

java,synchronization
I have an object named "Plan". There is an interface called "PlanService" that provides APIs to call CRUD operations on "Plan". PlanServiceImpl is the implementer which actually implements CRUD operations on Plan. Now I want to synchronize the CRUD operations on Plan in such a way that if callerA is...

Synchronize disabling of animation in iOS?

ios,animation,uiview,synchronization
I use some various blocks which looks like the following example: [UIView setAnimationsEnabled:NO]; ... [UIView setAnimationsEnabled:YES]; As I understand they may be called in a background thread and I should prevent mixing of disable/enable commands. How to do it correctly?...

Multiple threads waiting on the same event handle in C++

multithreading,visual-c++,asynchronous,synchronization,thread-safety
Summary If multiple threads are concurrently waiting on the same event handle, as in: WaitForSingleObject(theHandle, INFINITE); and the event is initialized to be manual-reset, as in: // manual-reset and initial-state set to true theHandle = CreateEvent(nullptr, true, true, nullptr); then once the event is set, will all threads resume? A...

Synchronized threads behaviour

java,multithreading,synchronization
I have a Cell class representing a single value and swapThread class whose run method just call the method swapValue() in Cell. public static void main(String[] args) throws InterruptedException { Cell c1 = new Cell(15); Cell c2 = new Cell(23); Thread t1 = new swapThread(c1, c2); Thread t2 = new...

Bound wait to solve race condition

algorithm,process,operating-system,synchronization,race-condition
I am trying to Give a race condition example , then write an algorithm to impose synchronization and write an algorithm that implement the Bounded wait solution?! I tried the case of when two admins A and B in the school receive 2 students to register them if they hit...

synchronized method in for loop

java,multithreading,synchronization,synchronized
In the following simple example code (mainly taken from this nice udemy video) there are two threads that increment a count instance variable through a synchronized method. This method however is inside a for loop in each thread. My question is: In a case like that, is it possible that...

Loop over multiple UIAlertController's

swift,synchronization,uialertcontroller
In some cases my applications needs to display muliple Alert messages. Error messages are gathered on start and needs to be displayed to the user one at a time. When the first one is acknowledged, the next one should be presented. The problem is that they all try to execute...

Why is the following Vector code broken exactly?

java,synchronization
follows from : Synchronization in Vectors in Java Why is the below code broken as far as synchronization is considered? Is the vector class not synchronized on its own object (this)? // BROKEN CODE, needs external synchronization // only add an element if the vector is empty if(vector.isEmpty()) vector.add(anElement); UPDATE:...

Thread synch and singleton questions

java,multithreading,synchronization,locking,singleton
First off I need to clear something basic, assume I have a synchronized block or a synchronized method and one thread already entered the synchronized part and 5 new threads try to access the synchronized part, will they stop running until the first thread leaves the synchronized part? and if...

Best practice to throttle concurrent calls

c#,asp.net,synchronization
I need advice on the best practice for throttling calls to code within an asp.net MVC web application. We have a class that handles some complex work involving calling out to Salesforce, let's call it ComplexSfLogic.cs. Salesforce has a limit of 10 concurrent requests at a time, and given the...

How to understand if wait() returned from timeout or from a notify()?

java,multithreading,synchronization
I have a waiting thread: synchronized(sharedCounter) { while(sharedCounter > 0) { sharedCounter.wait(60000); //wait at most 1 minute /*if it wakens from the end of the timeout, it should break the loop or it could potentially restart the timeout*/ } } And a thread that can notify: synchronized (sharedCounter) { if(sharedCounter...

How to handle asynchronous callbacks within an if - else statement?

node.js,if-statement,asynchronous,synchronization
For a project I need to alter some values in a file in five if-statements that are executed one after another, and after all those things are done, I need to save the file. One of the alteration contains an asynchronous save image function. The problem I'm having is that...

Syncronize thread to wait for multiple threads

java,multithreading,file-io,synchronization
I have four threads makes processing on four files, then I want a thread to concatenate these files. My solution is to make a fifth thread (thread1) to concatenate. sum = new Thread() { public void run() { if (thread1.isAlive()) { synchronized (lock1) { while (thread1.isAlive()) { try { lock1.wait();...

How to achieve synchronization in DB update when application is running on multiple nodes?

java,database,multithreading,synchronization,high-availability
I am new to J2EE development and trying to get some basics right. So the doubt is like, suppose I have an employee table somewhere in a database and a function which increases the salarycolumn in employee table. public synchronized IncreaseSalaryResponse increaseSalary(int empId, long raise); In my case the service...

From C# via CLR book: synchronization by reference and value types

.net,synchronization
Please, what do you think what output will be appeared in console (kind of trivia): Sync by reference type: class Program { static int x = 8; static object obj = new object(); static void Main(string[] args) { Thread t1 = new Thread(new ThreadStart(f1)); Thread t2 = new Thread(new ThreadStart(f1));...

Java synchronization in web service

java,multithreading,web-services,concurrency,synchronization
I have a java restful webservice program thats hosted on tomcat. In one of my web service methods, I load a big arraylist of objects (about 25,000 entries) from redis. This arraylist is updated once every 30 mins. There are multiple threads reading from this arraylist all the time. When,...

GCD custom queue for synchronization

objective-c,synchronization,grand-central-dispatch
In Mike Ash's GCD article, he mentions: "Custom queues can be used as a synchronization mechanism in place of locks." Questions: 1) How does dispatch_barrier_async work differently from dispatch_async? Doesn't dispatch_async achieve the same function as dispatch_barrier_async synchronization wise? 2) Is custom queue the only option? Can't we use main...

How to synchronize readout of binary streams on serial port of Matlab

matlab,serial-port,synchronization
I'm having an issue which is partially Matlab- and partially general programming-related, I'm hoping that somebody can help me brainstorm for solutions. I have an external microcontroller that generates a large stream of binary data (~40kb) every 400ms and sends it via UART to a PC running Matlab scripts. The...

Synchronized statements from different classes

java,synchronization
I have two classes B and C that implements the interface A. In both classes exist a method with a statement that needs to be synchronized. I have this: class B implements A { @Override public void method(){ //some code here synchronized (this.getClass()) { //some code here } } }...

How to create a synchronized object method in scala

scala,synchronization
Does scala support synchronized object (/static) methods? I am looking for: synchronized def myObjectMethod(): <SomeReturnType> = { .. } If this were not supported, what is the equivalent in scala ?...

dispatch_async doesn't go into loop

objective-c,synchronization,grand-central-dispatch
I need to fill in array. I have two methods. First of this create object that need to be added to array. I do it like this: __block NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:inputArray.count]; dispatch_queue_t queue =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_sync(queue, ^{ dispatch_apply(inputArray.count,queue , ^(size_t index) { [array insertObject:[self getObject:[inputArray objectAtIndex:index]] atIndex:index];...

Scope of synchronization on .class objects in the JVM

java,class,jvm,synchronization,locking
Let's say I've got the following code: synchronize (Test.class) { ... } Does this mean that the Test.class objects is locked for every other program running in the same virtual machine? Or does this lock only affect this one program in the JVM? If it affects every program: When Test.class...

rally synchronize lookback and alm

synchronization,rally,alm,lookbackapi
Is there any way to manually trigger a sync between lookback and alm. I just was running some lookback queries and the ETLDate was 3.8 hours out of sync. That seems like a pretty long time. If it is notyou could throttle the requests to a maximum of 1 per...

Use of if clause in OpenMP

synchronization,task,openmp
Can't figure out the use of the if (0) clause in the following code as there also exists the #pragma omp single clause. Any ideas? ...

Deployment synchronization Issue - API Manager 1.8

deployment,synchronization,wso2,wso2carbon,wso2-am
I have clusted the WSO2 API Manager 1.8 and implemented deployment synchronization according to this guide which is given in the WSO2 documentaion. Everything happens to work find except one thing. Let's assume that we have below 2 instances running API Manager. 192.168.X.123 - API Manager 1 192.168.X.124 - API...

When should I use a upgradable lock?

multithreading,boost,synchronization
I have used sharable lock and exclusive lock, but I don't have the opportunity to use upgradable lock. If there is a need to upgrade from sharable lock to exclusive lock, just unlock the sharable lock and get the exclusive lock. So under what situation should I use the upgradable...

Synchronization of property access with Class Lock

c#,.net,properties,synchronization,locking
Please consider the following code public class DataModel { public int a { get; set; } } public static class StaticAccess { private static _Data = new DataModel(); private static DataModel Data { lock(_Data) { return _Data; } } } Will an access to property a such us StaticAccess.Data.a =...

Difference between getAndSet and compareAndSet in AtomicBoolean

java,synchronization,atomicity,atomicboolean
The thread title should be self-explnatory... I'm a bit confused between the specification of below methos from AtomicBoolean class: java.util.concurrent.atomic.AtomicBoolean#compareAndSet java.util.concurrent.atomic.AtomicBoolean#getAndSet My assemption is that both would result in the same behavior when used as a boolean clause in an if condition: public class Test { private AtomicBoolean flag =...

How to sync the clocks in Raspberry Pi?

python,python-2.7,synchronization,raspberry-pi,clock-synchronization
I'm new to raspberry pi, trying to send a stream of bits from sender to receiver. However bits are not received in correct pattern most of the times, they seems to be shifted a little. I think i'm unable to synchronize them properly. Does anyone how I can sync the...

Play music synchronous using 3 MediaPlayer Objects on Android/Eclipse

android,eclipse,synchronization,android-mediaplayer
What i have: I have implemented three MediaPlayer.Objects in my App. All Three are created using a thread: protected void onResume() { // Threads mTT1 = new TrackThread(this, R.raw.audiofile1, 1, mHandler); mTT2 = new TrackThread(this, R.raw.audiofile2, 2, mHandler); mTT3 = new TrackThread(this, R.raw.audiofile3, 3, mHandler); // start thread mTT1.start(); mTT2.start();...

AtomicBoolean vs Synchronized block, whats the difference

java,concurrency,synchronization,boolean,atomicity
I am trying to understand the difference between the two following code blocks AtomicBoolean ab = new AtomicBoolean(false); using the following to get and set state. . ab.get(); ab.set(X); vs. private boolean ab = false; private final Object myboollock = new Ojbect(); public void setAB(boolean state) { synchronized(myboollock) { ab...

Sync TFS workitems so same WI is shown in two team projects

tfs,synchronization,tfs2013,tfs-workitem
Our team has an a TFS project in which we keep all the teams work. Sometimes some from our team are involved in another project that has it's own TFS project. The tasks that the people from our team does on the other project are in their own area. Is...

Using RAII for callback registration in c++

c++,c++11,callback,synchronization,raii
I'm using some API to get a notification. Something like: NOTIF_HANDLE register_for_notif(CALLBACK func, void* context_for_callback); void unregister_for_notif(NOTIF_HANDLE notif_to_delete); I want to wrap it in some decent RAII class that will set an event upon receiving the notification. My problem is how to synchronize it. I wrote something like this: class...

How to make sure synchronization using the Microsoft Sync Framework was successful?

c#,.net,sql-server,synchronization,microsoft-sync-framework
I am using the Microsoft Sync Framework to synchronize a table on two Microsoft SQL Servers. I have created a test application which generates one row per second in the table on the remote server. The application making use of the Sync Framework runs on the local server. The test...

What synchronization primitive should I use to implement a event driver framework in Java?

java,synchronization,locking,event-driven
I have a looper thread to execute tasks. Other threads can submit tasks to this looper thread. Some tasks are immediate tasks, others are future tasks, which are to be executed after T seconds after submission. I use PriorityBlockingQueue to store tasks, where time is used as the priority, so...

Most efficient way to process multiple callbacks into one receiver function

java,callback,synchronization
I have a async API that provides the output via a callback method. Now, I have to call this API N number of times simultaneously and then wait for N number of hits/callbacks to the callback method. In order to achieve this, I have currently used a counter and synchronized...

How to add syncronization properly Java

java,multithreading,synchronization
As the integers are produced the Consumer thread sums their value (1+2+3…+10=55) Producer thread generates integers from 1 to 10 The program is meant to produce an integer and consume it right away. But, the result generated at the program’s end rarely equals 55. This is because the threads don’t...

How to avoid concurrent access to a resource?

java,multithreading,synchronization,completable-future
I have four threads runs asynchronously using CompletableFuture as shown below in the code. and all of them should access "grownSeedXYList". sometime when i run the code i receive no errors, but some time i receive "java.util.concurrent.completionexception" and i thinkk this is because the "grownSeedXYList" is not synchronized. please let...

Java: Why is my synchronized output still so random

java,synchronization
So I'm practicing with synchronization for the first time. I'm trying to implement a practice concept that was described in general on the Oracle Java Concurrency tutorial. The idea is to have a special Counter object, with methods to increment, decrement, and show value. My goal was to get it...

Synchronise Python distribution across multiple Macs

python,osx,synchronization,dropbox
Does anyone know if there is a way to keep the Python libraries on both of my macs synchronised? I am just getting into Python, and really enjoying using it! I have two macs, and I keep my Python documents in Dropbox, so that they are accessible from both computers....

Bi-Directional Sync on Android Using SyncAdapter

sqlite,synchronization,android-contentprovider,android-syncadapter
I am planning to create sqlite table on my android app. The data comes from the the server via webservice. I would like to know what is the best way to do this. Should I transfer the data from the webservice in a sqlite db file and merge it or...

Wait for all processes reach some point in program, then resume

c,linux,synchronization,fork
I have an application which creates many processes via fork(). At some point I want to pause them all and wait until all of them finish earlier tasks. Then start them all at once. for (int i = 0; i < N; i++) { if(fork() == 0) { //some operations...

Producer consumer not giving desired result

java,multithreading,synchronization,producer-consumer
I'm learning thread synchronization from java documentation. I implemented a famous problem Producer-consumer problem. But it is not giving result as expected. I've searched a lot about this problem at HERE, HERE, HERE, HERE, HERE and some other stack-exchange and non-stack exchange sites but unable to resolve my problem. Here...

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,...

Android Parcelable Object Between Activities Clone

java,android,object,synchronization,parcelable
I have a class that implements Parcelable interface with all required read write methods. These are important methods of my parcelable object... ... public News() { // Default constructor... } @SuppressWarnings("unchecked") private News(Parcel in) { this.feedId = in.readLong(); this.ownerId = in.readLong(); this.author = in.readParcelable(User.class.getClassLoader()); this.ownerUserName = in.readString(); this.title = in.readString();...

Making multi callback synchronized with jQuery $.when

javascript,jquery,asynchronous,synchronization,jquery-deferred
This is my sample code: function out(msg) { $('#output').append(msg + '<br>'); } var myDeferred = []; $.each([8, 3, 4, 6, 9, 15, 7, 1], function (index, time) { myDeferred.push($.Deferred(function(dfd) { setTimeout(function () { out(time); dfd.resolve(); }, time * 1000); }).promise()); }); $.when.apply($, myDeferred).then(function () { out('all is done'); }); <script...

Using .NET 3.0 What is a good replacemet for thread resume and suspend

c#,multithreading,synchronization,.net-3.0
I am restricted to .NET 3.0: this is an externally imposed requirement. I need to process strings from a Generic.Queue. The main thread will Enqueue strings and the worker thread will Dequeue strings and then process them. At the top of the worker thread, it suspends itself and waits to...

Thread synchronization printing strings

c#,multithreading,synchronization
I wrote a small programm which prints "x", then "+", then again "x" and so on. The idea was to make it run in two threads so that the first thread prints "x" and the second prints "+". The output looks like this: "x" -> Thread number 1 "+" ->...

Concurrent reads from read only fields and writes in read/write fields in a shared object

java,multithreading,synchronization
Lets say that I have this class: public SharedObject { private int readOnlyField; private int readWriteField; public SharedObject(int field1, int field2) { this.readOnlyField = field1; this.readWriteField = field2; } public getField1() {...} public synchronized getField2() {...} public synchronized setField2(...) {...} } Can I have multiple threads that use these 3...

Make singleton observer pattern synchronized?

java,synchronization
When I have a common singleton pattern like the one above: To make it thread save, I made the access to adding and removing listeners synchroinized on the list of the listeners. But is it important to do this with every access on every listener? For example, should the same...

The method synchronizedMap(HashMap) is undefined for the type Collections

java,gwt,collections,synchronization
In my GWT client-side code, I have a class as follow public class SomeClass { private Map<Integer, Serializable> mId2ContentMap; private Map<Integer, Timestamp> mId2Timestamp; public SomeClass() { mId2ContentMap = Collections.synchronizedMap(new HashMap<Integer, Serializable>()); mId2Timestamp = Collections.synchronizedMap(new HashMap<Integer, Timestamp>()); } } When I try to run my GWT web application, I got two...

Does wait() need synchronization on local variable

java,multithreading,synchronization
I had this code (which was working fine): public static void runOnUiThread(Activity c, final Runnable action) { // Check if we are on the UI Thread if (Looper.getMainLooper() == Looper.myLooper()) { // If we are, execute immediately action.run(); return; } // Else run the runnable on the UI Thread and...

time synchronization on several Android devices

android,time,synchronization
Can I synchronize one time on several Android devices? For example current time is 00:00 and through the timeapi (web service) we sent this time to Android1. Due to some delay we get 00:01 instead of 00:00. We make the same on Android2 but in this time, delay = 2sec...

Java Multithreading null pointer exception

java,multithreading,synchronization
I'm working on this program and I keep getting a null pointer exception and I'm not sure why. //Constructor public LongTask(SharedResults sharedData,int start, int end) { super("Thread"); sharedData=this.sharedData; start = this.start; end=this.end; } //Run public void run() { int sum = 0; for (int num = start; num<=end;num++) { sum+=num;...

Threads working at the same time

java,multithreading,synchronization
I am trying to make my class as Queue such that if I have two threads, one that adds and other that removes elements - they could do that at the same time. Currently one gets blocked because the threads are competing for the same lock object. public class Queue...

Time accuracy improved starting with iOS 8.2?

ios,synchronization,apple-watch,ntp
My app uses an NTP server to get a more precise time than the iOS system clock. However, a poster at http://watch.camp/2014/11/apple-watch-timekeeping-accuracy/ suggests that with iOS 8.2, the iOS system clock is much more accurate because it's used to keep the Apple Watch within 50ms of true time. Can I...

IBM Connections 5 custom theme not getting published to second cluster node

synchronization,themes,cluster-computing,ibm,connections
we have the following small cluster setup: Server 1: DMGr, Nodeagent, Connections_server1 Server 2: Nodeagent, Connections_server2 All shared resources (including the customization dir) are on a separate file server that is linked on /opt/IBM/Connections/data/shared on both servers. I want to customize the defaultTheme, so I copied it to /customizationDir/themes/defaultTheme/custom.css After...

How can one synchronize an external application with a DigitalMicrograph script?

events,synchronization,external,dm-script
This question has been inspired by the question 'Call script from command line'. How can one write a script which acts on 'trigger events' in an application other than DigitalMicrograph? i.e. some script functionality should be triggered by an external application....

Pattern to communicate with a thread

java,multithreading,design-patterns,synchronization,nonblocking
I have a class OuterClass that contains a List and there is a thread ListWorker that is started in OuterClass that is adding some elements to the list. Based on a function call to OuterClass , it should be able to inform the thread to delete elements. What is the...

Synchronize global values between processes in NodeJS

node.js,synchronization,thread-safety
In NodeJS, I have two asynchronous functions that manipulate a single global value, here's an example: var someValue = 0; function longTask { // ... // very long process here // ... someValue += incrementValue; // modify value // ... // very long process again // ... } function shortTask...

Acquire mutex with preference for elevated process

c++,windows,winapi,synchronization,multiprocessing
I have a Mutex to avoid several processes from running at same time that could be waiting to start once the Mutex is released. Now I could have some instances trying to acquire a Mutex elevated and non elevated. I would like elevated processes to be able to acquire the...

Memory visibility guarantees provided by intrinsic locking in Java?

java,multithreading,synchronization,locking,volatile
I need some clarity on what memory visibility guarantees are provided by using an intrinsic lock in Java. So for example say if I have a HashMap object that maps Strings to Person objects like so: HashMap<String,Person> m = new HashMap<String, Person>(); And lets say we have a synchronized method...

OCaml, Sync on two events simultaneous with “and”

multithreading,events,synchronization,ocaml
I wrote an short program with 6 threads and 3 channels. 3 Threads are sending on 2 channels simultaneous and the other 3 are receiving. The problem is now, that it seems, that a sending thread takes one channel, but if it can't take the second one, it keeps the...

Is a __block variable assignment thread-safe to read immediately after the block?

ios,objective-c,synchronization,thread-safety,objective-c-blocks
__block NSHTTPURLResponse *httpResponse; dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { if (!error) httpResponse = (NSHTTPURLResponse *)response; } dispatch_semaphore_signal(semaphore); }]; [task resume]; dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); Is it safe to read httpResponse after this? The semaphore waits for the block to compete execution. If...

How to synchronize downloaded emails from clients back to the IMAP server

synchronization,imap,postfix-mta,data-recovery,dovecot
I have an iRedMail server running (postfix + dovecot as an IMAP server) on a Debian Xen guest machine. By a mistake the iscsi disk, where users emails are stored, was deleted. There is another copy of this disk from December 30th 2014. There is a full backup of users...

Is synchronized enough to make the drainTo() method of a BlockingQueue atomic?

java,multithreading,synchronization
If I simply do something like this: synchronized(taskQueue) { //taskQueue is a BlockingQueue taskQueue.drainTo(tasks); //tasks is a list } Am I assured that concurrent calls to taskQueue.put() and taskQueue.take() can not be executed inside the synchronized block? In other words, am I making the drainTo() method atomic? Or more generally,...

Error assigning value to JavaScript class property

javascript,node.js,asynchronous,synchronization,prompt
I am getting an error while setting a class property in javascript class. I am using nodejs prompt module to get user input and setting it to the class property. But i am getting following error. TypeError: Cannot read property 'resultAge' of undefined I figured it out that it has...

Can POSIX named semaphores synchronize threads?

multithreading,synchronization,posix,semaphore
I am looking for a way to synchronize several multi-threaded processes on Linux. C++11-style mutexes only operate among threads within a single process, ans as far as I know, flock doesn't mutually excludes threads of the same process. Therefore, I was thinking of POSIX semaphores. I know that unnamed semaphores...

Using callbacks instead of promises in AngularJS results in different behavior in unit tests. Why?

angularjs,callback,scope,synchronization,promise
I'm testing a $resource. If I have code like this: $resource.do(stuff).$promise.then(function(data){ console.log(1); }); console.log(2); I get the print out: 2 1 But if I have code like this: var callback = function(data){ console.log(1); } $resource.do(stuff,callback); console.log(2); I get the print out: 1 2 Why? I have found that with the...

Does syncronised if apply to whole block

java,synchronization
This is not a question about method syncronisation, only to statement syncronisation. Please do not incorrectly mark as duplicate. Is this code: syncronized (this) if (something) { somecode(); somemorecode(); } equivalent to this code: if (something) { syncronized (this) { somecode(); somemorecode(); } } ...

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...

Making multiple ajax requests synchronously

javascript,jquery,ajax,asynchronous,synchronization
Let's suppose I have some function called makeRequest(), which makes an AJAX request to a server. Now let's suppose I am given the amount of times this request should be made, but I can't do them asynchronously but synchronously instead. For instance, I am given the number 5, and I...

Synchronization: Why is it preferred to lock a private final static object instead of the class's class object?

java,multithreading,synchronization
Simple question: Why would this be preferred: public class Foo { final private static Object foo = new Object(); public static void doSomething() { synchronized(Foo.foo) { //code } } } over this: public class Foo { public static void doSomething() { synchronized(Foo.class) { //code } } } or this: public...

Javascript Date() intialization in bad format

javascript,node.js,datetime,synchronization
I'm writing javascript multiplayer game, my server code is in nodejs. I need to synchronize time between server and client. At server side i call Date() and send the date string to client. Client recieves: Tue Apr 28 2015 15:37:01 GMT+0000 (UTC) After initialization with: var time = Date("Tue Apr...

Interleaving processes on two threads

c#,multithreading,synchronization
I have a library that I can use to access some tabular data. This library is the only way I have of accessing the data. The method I am using takes a query string and a callback that is called for each result row. Currently, the callback loads each row...

Stop all threads in a custom thread pool (like shutting down)

java,multithreading,synchronization
In Java library thread pool implementations, usually shutting down a pool means: -stop accepting new tasks -previously submitted tasks are executed -all pool threads are terminated Regarding the last point, how would you stop a pool thread that could potentially try to take a new task, after it has been...

Process synchronization using semaphores

operating-system,synchronization,semaphore
I want to know if my approach in the following case is correct or not: There are 5 processes P1, P2, P3, P4 ad P5. And they can execute as follows: • P1 can start any time. • P2 can start after P1 completes. • P3 can start after P1...

NodeJS cache mysql data whith clustering enabled

mysql,node.js,synchronization
I want to cache data that I got from my MySQL DB and for this I am currently storing the data in an object. Before querying the database, I check if the needed data exists in the meantioned object or not. If not, I will query and insert it. This...

How does StringBuffer synchronization work?

java,multithreading,synchronization,stringbuffer
Greetings to everyone! I'm a bit confused as to in what way/under what circumstances StringBuffer is synchronized and prevents multi-threaded access. In the code below it prints out the letters in the for loop A 100 times then B 100 times etc... comment out the synchronized (sb){} part and it...

Why do thread behave different with different run method body?

java,multithreading,synchronization,volatile
This code is from Effective Java (Item 66): (without sync or volatile this never ends) public class ThreadPractice { static boolean canrunstatic; public static void main(String[] args) throws InterruptedException { Thread backgroundThread = new Thread(new Runnable() { public void run() { int i = 0; while (!canrunstatic){i++;} System.out.println("finished"); } });...

Best practices in syncing data

synchronization,sync,offline-caching,offlineapps
Context A mobile application can add/edit/delete a customer in it's own offline database. A web application can also add/edit/delete a customer in the master database on a web server. The mobile application will try to sync it's database with the master database every X hours, provided it has an internet...

How to properly leave a Critical Section?

c++,windows,exception,exception-handling,synchronization
I have the following C++ code where I make use of the Critical Section object: EnterCriticalSection(&cs); // code that may throw an exception LeaveCriticalSection(&cs); How can I ensure that the LeaveCriticalSection function is called even if an exception is thrown?...