FAQ Database Discussion Community


JavaEE Web JAX-RS: can i use instance variables inside it's class?

java,thread-safety,jax-rs
I'm looking for thread-safe Servlet alternative and I've found JAX-RS technology. So can i use instance variables inside it's class like this (is it thread safe): @Path("helloworld") public class HelloWorldResource { private String msg; @GET public void doSmth() { this.msg = "test"; } } ?...

C - safety when accessing an integer variable: 1 writer, N readers

c++,c,multithreading,thread-safety,atomic
I've a "static 64-bit integer variable" that gets updated by only one thread. All other threads only read from it. Should i protect this variable using atomic operation (ex. "__sync_add_and_fetch") for safety reasons? Or is it OK to read(resp. write) from (resp. to) it directly? I'm still confused because i...

TextArea.continueCursor(TextArea.java:331) / ArrayIndexOutOfBoundsException: 16

user-interface,libgdx,thread-safety,indexoutofboundsexception
What could be the cause of this error? (Can't figure it out) Exception in thread "LWJGL Application" java.lang.ArrayIndexOutOfBoundsException: 16 at com.badlogic.gdx.scenes.scene2d.ui.TextArea.continueCursor(TextArea.java:331) at com.badlogic.gdx.scenes.scene2d.ui.TextArea.calculateOffsets(TextArea.java:278) at com.badlogic.gdx.scenes.scene2d.ui.TextField.draw(TextField.java:283) at com.badlogic.gdx.scenes.scene2d.Group.drawChildren(Group.java:124) at com.badlogic.gdx.scenes.scene2d.Group.draw(Group.java:58) at...

TThreadList and “with” statement

multithreading,delphi,thread-safety,locking
just a short question regarding how to use TThreadList. Is it safe to use it with "with" statement as follows: with FEngineList.DAQEngines.LockList do begin try for Idx := 0 to Count - 1 do Items[idx].Param1 := cos(2*pi*I/Count); ... ... finally FEngineList.DAQEngines.UnlockList; end; end; or should I explicitly do it like...

Threading synchronization - balking pattern

c#,multithreading,thread-safety
public class Example { private boolean jobInProgress = false; public void job() { lock(this) { if (jobInProgress) { return; } jobInProgress = true; } // Code to execute job goes here // ... } void jobCompleted() { lock(this) { jobInProgress = false; } } } I got this piece...

Iterator type in java (weakly consistent)

java,multithreading,iterator,thread-safety
I understand fail-fast (LinkedList) and fail-safe (copyonwrite) iterators, however weakly consistent remains a mystery. Documentation says it might reflect the changes of the underlying collections but there is no guarantee. So I assume that weakly consistent do not create copy of the backing collection. (in a concurrent Map it works...

Is thread safe to assign a shared_ptr nullptr?

c++11,thread-safety,shared-ptr
Suppose there is a shared_ptr: std::shared_ptr<MyClass> myPtr = std::make_shared(new MyClass()); In worker thread: myPtr = nullptr; In main thread: if( myPtr != nullptr ) { // do something } Is the code above thread safe? Or can the main thread see the new value immediately?...

Tool for java that uses annotation to monitor/log/report threads accessing given method?

java,multithreading,thread-safety,aspectj
Context: I have created a small (java) multithread server for a game. Despite my best efforts of following the best practices it turned out that some methods that were intended to be called from just one thread got called from 2 or more threads. After debugging and analysis I have...

Is CreateToolhelp32Snapshot function thread safe?

c++,windows,winapi,process,thread-safety
As title, I can't find any information about whether CreateToolhelp32Snapshot, Module32First and Toolhelp32ReadProcessMemory function WinAPIs is thread-safe or not. Dose anyone know about this? Or is there any way I can figure out whether those APIs are thread-safe? MSDN: Tool Help Functions...

Python thread locks vs forced timer delays

python,multithreading,thread-safety
Its my understanding that when you implement a global lock in Python, this should reserve stdout for the thread that activates the lock, and therefore prevent other threads from utilizing stdout until the thread releases the lock. Doesn't this means that in the following code, the loop in thread "a"...

Java - using Thread instead of SwingWorker [duplicate]

java,multithreading,swing,thread-safety,swingworker
This question already has an answer here: Why SwingWorker? Why not just Thread or Runnable? 4 answers I cannot really get the advantage of using a swingworker instead of just simply putting the heavy task in a (simple) background-thread. This is just a codesnippet but shows the task of...

What's the significance of .NET ReaderWriterLock's “-1 milliseconds”

.net,multithreading,thread-safety
The .NET ReaderWriterLock methods' documentation, such as AquireReaderLock ( https://msdn.microsoft.com/en-us/library/87cwd104(v=vs.110).aspx ) explicitly mentions a timeout value of -1 milliseconds as a valid timeout, but fails to state what this value represents. Does this mean that the lock fails immediately, like a TryLock? Does it mean that the lock will never...

Atomic operations on memory mapped files

multithreading,go,thread-safety,atomic
I'm using a memory mapped file and I need to use an atomic store on Go. I would use StoreUint64() if I were working on regularly allocated memory. However, I'm not sure how atomic operations work on memory mapped files. Is it safe to use StoreUint64() on memory mapped files?...

Update Int32 in Task c#

c#,multithreading,thread-safety,task-parallel-library,task
is there any way to increment a value of an int inside a task? or is this a correct syntax in incrementing an int in task? sample code: public int erCount = 9; static void Main(string[] args){ Task.Factory.StartNew(() => { ...do some task if(errorfound) erCount++; }); Task.Wait(); Console.Writeline(erCount.toString()); } I...

Use separate subs without invoking proporties

.net,vb.net,multithreading,thread-safety,invoke
I am trying to achieve a linear code without any "background workers" running alongside my main program (with the exception of a few System.Windows.Forms.Timers). I'm using Private Subs in order to eliminate the need to copy and paste, for example, the same 50 lines of code 10 times in my...

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

Varible set in another thread does not obtain/retain value

c#,multithreading,thread-safety
I attempt to set the value of a classes property in another thread, but the property/variable dose not obtain that value. Why is this, and how can I fix it. Here is simple tested code demonstrating the problem using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using System.Runtime.InteropServices; namespace Tests...

Is java.awt.GraphicsConfiguration thread-safe? What are the alternatives

java,thread-safety,awt,bufferedimage,swingworker
I'm extending javax.swing.JComponent to display a variable number of tiles, which all have the same size. If a tile needs a new appearance, a SwingWorker's doInBackground() renders a new BufferedImage for it. In done(), the image is stored and JComponent.repaint() is called, indicating the updated area and an intended delay....

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

Thread Safety in Jax-WS Request-Response Payload Logging

web-services,soap,thread-safety,jax-ws,soaphandler
I am working on a SoapHandler implementation. Basically my aim is to get both request and response payloads and insert them to the database. Although I can get the request and response payloads, I couldn't make sure if my code is working thread-safe. In other words, I am not sure...

Does using private setters only in a constructor make the object thread-safe?

c#,thread-safety,immutability
I know that I can create an immutable (i.e. thread-safe) object like this: class CantChangeThis { private readonly int value; public CantChangeThis(int value) { this.value = value; } public int Value { get { return this.value; } } } However, I typically "cheat" and do this: class CantChangeThis { public...

How to add hostname to block list after consecutive failures in multithreading application?

java,multithreading,thread-safety,callable,atomicreference
I am using Callable in my code which will be called by multiple threads as shown below. As of now, whenever any RestClientException is thrown then I am adding hostname to blockList. public class Task implements Callable<DataResponse> { private DataKey key; private RestTemplate restTemplate; public Task(DataKey key, RestTemplate restTemplate) {...

Java: is CountDownLatch threadsafe

java,thread-safety,countdownlatch
In the docs for CountDownLatch I see something like: public void run() { try { startSignal.await(); doWork(); doneSignal.countDown(); } catch (InterruptedException ex) {} // return; } Here startSignal and doneSignal are CountDownLatch objects. The docs don't mention anything about the class being thread-safe or not....

Are Kotlin's singletons thread safe?

thread-safety,singleton,kotlin
Are Kotlin singletons (more specifically, object declarations) thread-safe by construction? If not, what is the best practice to write thread safe singletons in Kotlin? I would guess they are, but I haven't been able to find any explicit statement about it in the docs....

Can't figure out how to deal with these errors [duplicate]

java,swing,exception-handling,nullpointerexception,thread-safety
This question already has an answer here: What is a Null Pointer Exception, and how do I fix it? 12 answers i built a little software. The software runs perfectly ok as it should. On initiation of the software, a option pane pops up asking for name, user can...

Is StringBuilder threadsafe (using it with parallelStream)?

java,multithreading,thread-safety,java-8,stringbuilder
My code: StringBuilder sb; sb = new StringBuilder(); events.parallelStream().forEach((event) -> { sb.append(event.toString()); sb.append("\n"); }); I don't care about the order of the events.toString() in the final result. But I care that the events.toString() will correctly appear one line after another, without mixing / messing up of course. Is parallelStream (instead...

Ruby: Wait for all threads completed using join and ThreadsWait.all_waits - what the difference?

ruby,multithreading,thread-safety
Consider the following example: threads = [] (0..10).each do |_| threads << Thread.new do #do async staff there sleep Random.rand(10) end end Then there is 2 ways to wait when it's done: Using join: threads.each(&:join) Using ThreadsWait: ThreadsWait.all_waits(threads) Is there any difference between these two ways of doing this? I...

Thread safety in String class

c#,multithreading,thread-safety
Is it thread safe to build strings from local variables using the String class like in the methods below? Suppose that the methods below are called from several threads. public static string WriteResult(int value, string name) { return string.Format("Result: value={0} name={1}", value, name); } public static string WriteResult2(int value, string...

please re-compile PHP with ZTS enabled Mac OS X

php,osx,thread-safety,osx-yosemite
I trying to install pthreads on Mac Os X. When I execute: sudo pecl install pthreads I get error: checking checking for ZTS... configure: error: pthreads requires ZTS, please re-compile PHP with ZTS enabled ERROR: `/private/tmp/pear/temp/pthreads/configure' failed So the question is how to recompile php with ZTS enabled for OS...

Is Spring mongoTemplate thread safe?

java,multithreading,thread-safety,spring-mongo
I define this Bean: <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" /> <constructor-arg name="mongoConverter" ref="mongoConverter" /> </bean> and i instantiate a mongoOprations using this Bean, now i want To know Is Spring mongoTemplate thread safe?...

Update joinable() before closuer join() thread C++

c++,multithreading,thread-safety
How to manage thread like this: thread th(foo); while(th.joinable()) { // thread foo is active; // some printing from foo function for example } th.join(); This while is infinite because th.joinable() is always true and not updating. What reason and how to solve this problem?...

Singleton class and thread safety

c++,multithreading,thread-safety
class NumberStorage { public: static NumberStorage& instance(); double getNumber(); void setNumber(double d); private: NumberStorage() { number = 0.0; }; double number; }; ColorRamps& ColorRamps::instance() { static ColorRamps instance; return instance; } I think I have read somewhere that the instance() method implemented this way is thread safe. Is this correct?...

Calculating average and percentiles from a histogram map?

java,multithreading,timer,thread-safety,concurrenthashmap
I have written a timer which will measure the performance of a particular code in any multithreaded application. In the below timer, it will also populate the map with how many calls took x milliseconds. I will use this map as part of my histogram to do further analysis, like...

Executing Thread by run method and Start method

java,multithreading,thread-safety
I am trying to execute Thread into the Both method using thread.Run and as well as thread.start Here the case Main Class Thread thread = new GetTimeZones(); ByImletingInterface thread21 = new ByImletingInterface(); thread21.getMailStarttime(5); ByImletingInterface thread2 = new ByImletingInterface(); thread2.getMailStarttime(10); thread.start(); new Thread(thread21).start(); new Thread(thread2).start(); Thread 1 public class ByImletingInterface implements...

Update progressbar from thread- MVVM

c#,wpf,multithreading,mvvm,thread-safety
I am new to MVVM pattern. I have a problem updating progressbar from another thread. View.Xaml <ProgressBar Value="{Binding ProgressBarValue}"> ViewModel.cs public int ProgressBarValue { get { return status; } set { this.status = value; this.RaisePropertyChanged(() => this.ProgressBarValue); } } Thread th; private void OnOk() { th=new Thread(new ThreadStart(StartProcess)); } private...

Is this thread-safe in Java?

java,static,thread-safety
Is the following static method "contains" safe from a visibility perspective? public class MyTest { private static final HashSet<String> mySet= new HashSet<String>(); static { mySet.add("cat"); mySet.add("dog"); mySet.add("bird"); } public static boolean contains(String key) { return mySet.contains(key); } } So then if multiple threads call MyTest.contains(string) are they guaranteed to see...

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

What happen when I run MemoryBarrier() exactly ? and how do it?

c#,.net,vb.net,thread-safety,volatile
According to Web, I found the following codes, which is equivalent of C# Volatile for VB.NET. Code reference: How do I specify the equivalent of volatile in VB.net? Function VolatileRead(Of T)(ByRef Address As T) As T VolatileRead = Address Threading.Thread.MemoryBarrier() '*** I mean this line ***' End Function Sub VolatileWrite(Of...

How can I pop from a queue, process it, push to another queue, and it's thread-safe?

c++,multithreading,thread-safety,queue
It's a C++ program. There are 2 child thread and 2 queue.What I want to do is, Push something to the queue 1 in the main thread. The child thread 1 pop from the queue 1 and process it, then push it to the queue 2. The child thread 2...

BundleTable.EnableOptimizations is thread safe?

c#,.net,thread-safety,global-asax
I added a logic to my app in order to enable debugging production. I pass debug=true to the querystring, I set BundleTable.EnableOptimizations to false (and avoid optimize my js files) in Application_BeginRequest(). My Q is it thread safe? I try to run some tests by locking the code and it...

Can I move Delphi TThread.Synchronize() locally to a VCL form to be called from both a main or worker thread?

multithreading,delphi,thread-safety,anonymous-methods
I am using CreateAnonymousThread for a worker task, and when I started with it I used Synchronize within the entire declaration as per documented examples, e.g: procedure Txxx.RunWorker; begin FExecutionThread := TThread.CreateAnonymousThread(procedure () begin TThread.Synchronize (TThread.CurrentThread, procedure () begin // Here before worker stuff NotifyBeforeWorkerStuff; end); // Do worker stuff...

C# - why is Thread.Suspend() so bad?

c#,multithreading,thread-safety
Title says it all. I am running a Selenium web testing script that I want the ability to pause on user button click. Thread.Suspend() works perfectly, but I keep seeing everywhere about how you shouldn't use it, but no one really goes into to much detail as to WHY you...

Problems with big C# list, list is inaccessible

c#,list,thread-safety
Every time I do a List.add to one list bigger than 1000, I have a chance to get (Collection was modified; enumeration operation may not execute). If I increase the size, the problem happens more often. I have a lot of threads making a cache of info, and users getting...

Wait and Notify in Java threads for a given interval

java,multithreading,thread-safety,wait,notify
i am working on a usecase as below. I am new to multi threading and facing this issue with using it. I broadcast a event on network. Its received by all the listeners, and they unicast me with their information. This is received inside the call back method as below,...

C# how cancel an executing method

c#,multithreading,delegates,thread-safety
I have a delegate method to run a heavy process in my app (I must use MS Framework 3.5): private delegate void delRunJob(string strBox, string strJob); Execution: private void run() { string strBox = "G4P"; string strJob = "Test"; delRunJob delegateRunJob = new delRunJob(runJobThread); delegateRunJob.Invoke(strBox, strJob); } In some part...

Potential race condition in the timer class?

java,multithreading,timer,thread-safety
I have written a timer which will measure the performance of a particular code in any multithreaded application. In the below timer, it will also populate the map with how many calls took x milliseconds. I will use this map as part of my histogram to do further analysis, like...

Is it possible to restrict a member function from accessing a member variable?

c++,multithreading,thread-safety,chrono,stdatomic
I have a thread class similar to this: class thr { void run() { for (;;) { // block on a queue // do some processing ++loops_; } } void get_metrics(int& qps) { std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now(); double delta = std::chrono::duration<double>(now - last_metrics_time_).count(); qps = std::round(loops_ / delta); loops_ =...

Are the C functions recvfrom and sendto mutually exclusive?

c,linux,sockets,udp,thread-safety
I have one thread calling recvfrom with a timeout of 100 ms in a loop. Another thread calls sendto periodically. Does the sendto function wait until the recvfrom is released by the timeout (or a successful read) or does it send the data during that period of time....

Writing to JTextArea with CachedThreadPool

java,multithreading,swing,thread-safety
I asked this in CodeReview but it was closed. For a school assignment I have to create 54 threads that run simultaneously from a Executors.newCachedThreadPool() that write to a JTextArea in a thread safe manner. Each thread has to write 'A' through 'Z' to the field 1000 times. I've been...

How does Tomcat create threads internally?

java,multithreading,tomcat,thread-safety
I'm writing a Tomcat application which need to maintain some internal states across different requests, so I need share something between different threads created by Tomcat. My question is, if I write code like this, will Map (which is static to the class) be shared between threads created by Tomcat....

Thread safety in java for static methods

java,multithreading,thread-safety,static-methods
I have the following code //EDIT :- updated code with @Riaz's answer ( this code should be thread -safe now ) public final class MyClass { private static MyClass2 _class2; private MyClass() { } public static synchronized MyClass CreateMyClass1(String arg0 , ArrayList<MyClass3> class3) throws Exception { MyClass myClass = new...

Safe fire and forget method in Perl

multithreading,perl,exception-handling,thread-safety
I need to execute a method (not process) asynchronously in my Perl code, but I must ensure that this code will never raise any exception and stop my main task execution. What would be the best way to call a method asynchronously and silencing any potential exception whether it is...

Could calls to Writeln() from a thread cause another thread to intermittently miss incoming data from a serial port?

delphi,serial-port,thread-safety,delphi-xe2
A customer is beta testing a program for me. He is getting an intermittent error in which the program fails to detect an incoming character from a serial port, which indicates an external device has finished a task. Try as I may I, cannot repeat the problem in my office,...

C# CrossThreadMessaging on reading label text

c#,thread-safety
I have seen innumerous topics but all of them talk about updating the text value of a control not retrieving the value of it. I currently use the following function to avoid cross thread operations and works fine when calling functions or assigning values. private void ExecuteSecure(Action a) { if...

Pass NSManagedObjectContext between threads

core-data,thread-safety,nsmanagedobjectcontext
Is it safe to initialize NSManagedContext in one thread and then pass it to another thread where you do inserts/fetches inside performBlock: ? So https://stackoverflow.com/a/12876800/2645683 mentions performBlock: and relates to my question but its not sufficient. It doesnt explicity say anything about thread which created context, and thread that executes...

Guava AbstractScheduledService on server environment

java,thread-safety,guava,scheduler
What is the preferred way of shutting down an AbstractScheduledService running in server environment (e.g. Tomcat) when the application server is shutting down? Do I have to explicitly register a server listener for this, or is there a way to specify the service threads as daemons?

Why SendKeys.SendWait() crashes my application

c#,thread-safety,messaging,sendkeys
In my console application, SendKeys.SendWait("^c") is called to copy some selected text to the clipboard. It works fine, but if my console application has focus when this is called, then, instead of throwing an exception, it just closes my application. And then after that things start acting up, like my...

ASP.NET instantiating regex within a static method and thread safety

c#,asp.net,regex,.net-4.0,thread-safety
Taken the following class that is part of a ASP.NET HttpModule (and taken that I know about regex and html, I don't have a choice in this one though): sealed internal class RegexUtility { public static Regex RadioButton { get; private set; } static RegexUtility() { RadioButton = new Regex(@"<input.*type=.?radio.*?>",...

Thread start passed integer changes itself beyond what it should be [duplicate]

c#,multithreading,parameters,lambda,thread-safety
This question already has an answer here: Thread alters passed Int, if start() is called separately 1 answer I have no idea what is going on in this. I'm trying to test thread safety of a class by spawning 100 threads to access it constantly, but it seems my...

Java Garbage collection against Local and Global variable with Thread Safe

java,garbage-collection,thread-safety,global-variables,local-variables
Which of the below snip of code is more Garbage Collection efficient in terms of TIME Class Test{...} Local Variable private void function(){ Test test = new Test(); .... } Global Variable Test test = null; private void function(){ if(test == null){ test = new Test(); } } Let assume...

Why A single Jedis instance is not threadsafe?

redis,thread-safety,pool,jedis
https://github.com/xetorthio/jedis/wiki/Getting-started using Jedis in a multithreaded environment You shouldn't use the same instance from different threads because you'll have strange errors. And sometimes creating lots of Jedis instances is not good enough because it means lots of sockets and connections, which leads to strange errors as well. A single Jedis...

Python Gui (Tkinter) procces [closed]

python,user-interface,tkinter,thread-safety
This is my code: http://pastebin.com/eN6xZ40P I got two errors that I cannot understand: Exception in Tkinter callback Traceback (most recent call last): File "C:\python26\lib\lib-tk\Tkinter.py", line 1410, in __call__ return self.func(*args) File "D:/Users/user-pc/Desktop/mail/someTK.py", line 32, in sendMail msg = MIMEText(output['Body']) KeyError: 'Body' ...

It is safe to change variable values of a thread from the main thread?

delphi,thread-safety,delphi-2009
I wrote a simple component that monitors a folder and triggers an event when it detects changes. It works well... apparently. But I'm not sure of one thing. From time to time, the main thread may need to update the monitored path and I'm not sure if I've done this...

Thread safe SQLAlchemy session for Pyramid requests

python,sqlalchemy,thread-safety,pyramid
The article What the Zope Transaction Manager Means To Me (and you), demonstrates a nice way to attach an SQLAlchemy DB session to each request this way: def includeme(config): settings = config.get_settings() engine = engine_from_config(settings) maker = sessionmaker() register(maker) maker.configure(bind=engine) config.add_request_method(lambda request: maker(), 'db_session', reify=True) The problem with this approach...

Is it necessary to end a ThreadPool on Application.Exit()?

c#,thread-safety,threadpool,cancellation
I have a separate BackgroundWorker and ThreadPool that does methods in the background. (BackgroundWorker for UI feedback) ThreadPool: ThreadPool.QueueUserWorkItem(foo, null); I understand that I need to safely terminate my BackgroundWorker using a flag considering that it gives me an Exception if ever I close it without one. However, the ThreadPool...

Does FileShare.None make threads wait until the filestream is closed

c#,.net,file,thread-safety
When using a file stream, and setting FileShare to none, and say two users accessing the same function at the same time want to read/write to that file. Will FileShare.None make the second users request waiting or will the second user's request throw an exception? //two users get to this...

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

Implementing nonblocking thread-safe list

java,list,thread-safety,nonblocking
Is it possible to implement nonblocking thread-safe list using ConcurrentHashMap as a backing where you use the index as the key and elements as the values?

THREAD WARNING: ['Console'] took '81.661865' ms. Plugin should use a background thread

ios,thread-safety,phonegap-plugins,cordova-plugins,background-thread
Hi I am getting warning as : "THREAD WARNING: ['Console'] took '81.661865' ms. Plugin should use a background thread." while running iOS phone-gap project. Similarly for some of the remaining plugins like geolocation and filesystem. As I am new to phone gap ,can please anyone tell me how can I...

Why is this class not thread safe?

java,multithreading,thread-safety
class ThreadSafeClass extends Thread { private static int count = 0; public synchronized static void increment() { count++; } public synchronized void decrement() { count--; } } Can anyone explain why above class is not thread safe?...

is @Singleton in dagger 2 thread safe?

java,android,multithreading,thread-safety,dagger-2
I'm trying to move everything in my app away from singletons, because I've been made aware that it's a bad programming practice, with that said, I'm looking into implementing Dagger 2 dependency injection. And I'm wondering, when you do @Singleton in Dagger 2 is that thread synchronized? if not how...

Java Multithreading - Threadsafe Counter

java,multithreading,thread-safety,counter
I'm starting off with a very simple example in multithreading. I'm trying to make a threadsafe counter. I want to create two threads that increment the counter intermittently to reach 1000. Code below: public class ThreadsExample implements Runnable { static int counter = 1; // a global counter public ThreadsExample()...

Is Shiro's DefaultPasswordService thread safe?

java,multithreading,thread-safety,shiro
Can I have a single instance of DefaultPasswordService and call its encryptPassword() method without worrying about thread safety issues? The documentation doesn't make this clear....

ManualResetEvent Skipped by thread

c#,.net-4.0,thread-safety,manualresetevent
Here I have a block of code that executes: public override void Execute(XObjectList itemList, ProcessInfo processInfo) { ManualResetEvent syncEvent = new ManualResetEvent(false); execute(itemList, processInfo); //openScreen(); Thread STAThread = new Thread(() => { var window = new Window(); window.Content = new MailViewerView(); window.Show(); syncEvent.Set(); }); STAThread.SetApartmentState(ApartmentState.STA); STAThread.Start(); syncEvent.WaitOne(); } I expect...

To check whether thread's apartment type is MTA or STA?

c#,multithreading,winforms,thread-safety
Is there any way so that i can check the apartment type of thread,whether it is MTA or STA while debugging an application on runtime ? I am working on winforms application in visual studio 2008 IDE.

How to make sure my map is never modified once set in my Builder pattern?

java,multithreading,dictionary,thread-safety,final
Below is my builder pattern which I am using in one of my projects and I wanted to make it thread safe in multithreading environment. Once the ClientKey is set, I don't want anyone to modify it again. public final class ClientKey { private final long userId; private final int...

How to populate concurrenthashmap from multiple threads?

java,multithreading,thread-safety,concurrenthashmap
I have a ConcurrentHashMap which I am populating from multiple threads. private static Map<DataCode, Long> errorMap = new ConcurrentHashMap<DataCode, Long>(); public static void addError(DataCode error) { if (errorMap.keySet().contains(error)) { errorMap.put(error, errorMap.get(error) + 1); } else { errorMap.put(error, 1L); } } My above addError method is called from multiple threads which...

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

addAll() in LinkedBlockingQueue is thread safe (and solution if it's not)?

java,thread-safety,locking,blockingqueue
Quoting the documentation: "BlockingQueue implementations are thread-safe. All queuing methods achieve their effects atomically using internal locks or other forms of concurrency control. However, the bulk Collection operations addAll, containsAll, retainAll and removeAll are not necessarily performed atomically unless specified otherwise in an implementation. So it is possible, for example,...

What is the best way to work with multiple files in multithread in C#?

c#,multithreading,winforms,thread-safety
I am creating a Windows Form application, where I select a folder that contains multiple *.txt files. Their length may vary from few thousand lines (kB) to up to 50 milion lines (1GB). Every line of the code has three informations. Date in long, location id in int and value...

Problems with race conditions on ConcurrentHashMap

java,multithreading,concurrency,thread-safety,race-condition
I got a multithreaded application in which n threads write to an ConcurrentHashMap. Another n Threads read from that Map and copy its Value to a copy List. After that the original List is removed from the map. For some reason I always get a ConcurrentModificationException. I even tried to...

Updating UI From a background thread on iOS

ios,user-interface,background,thread-safety
On iOS, its well documented that the UI should never be updated from a background thread. Rather the main thread should be the sole interface to update the UI. My Question is why? Is it because UIControls are not thread safe and hence there is always the possibility of main...

Redis Cluster in multiple threads

multithreading,redis,thread-safety,connection-pooling,jedis
Im currently using Redis Cluster Mode with 3 master instances, i'm using Jedis(Java client) in listening server which every data received i create a new thread then the thread make an update in redis. My question is how can i use Redis Cluster instance in multiple thread with pool configuration....

Closing over java.util.concurrent.ConcurrentHashMap inside a Future of Actor's receive method?

performance,scala,thread-safety,akka,concurrenthashmap
I've an actor where I want to store my mutable state inside a map. Clients can send Get(key:String) and Put(key:String,value:String) messages to this actor. I'm considering the following options. Don't use futures inside the Actor's receive method. In this may have a negative impact on both latency as well as...

Is there any way to disable a windows.form.timer inside a Task?

c#,timer,thread-safety,task
Is there any way to disable a windows.form.timer inside a task? here is an example code that I have. private void timer1_Tick(object sender, EventArgs e) { Task.Factory.StartNew( () => {runTask();} ); } private void runTask() { //Process here.... timer1.enabled = false; MessageBox.Show(timer1.Enabled.ToString()); } When I run the program the value...

is this java blocking queue variant possible?

java,multithreading,thread-safety,blockingqueue
The following scneario is what i was thinking of: - 2 Threads, 1 Producer, 1 Consumer - T1 creates the Queue and starts the next thread, and is repsonsible for puting elements into the queue ServerThread implements Runnable{ run(){ BlockingQueue q = new ArrayBlockingQueue(1024); ListenerThread lt = new ListenerThread8(q); lt.start();...

Best way to handle ERESTARTSYS in kthread?

thread-safety,kernel,kernel-module
I have a kthread that blocks on a wait event until a timeout is reached. However, if a system event interrupts it (such as the system going into suspend), it returns -ERESTARTSYS. I'm curious to know how to handle this situation, since I don't want the kthread to die, just...

How to write a IEnum thread

c#,multithreading,thread-safety,locking
I am trying to write a small threaded application and wanted to know how I could implement the below IEnum as thread/threaded? Absolute beginner to threading, not even sure the below method can be threaded. Would appreciate a little walk through. static void Main(string[] args) { IEnumerable<string> e = Enumerable.Range(1,...

Is this BlockingQueue Thread safe?

c#,thread-safety,blockingqueue
I was trying myself on implementing a minimal thread safe blocking queue, what I came up with is: class BlockingQueue<T> { private Queue<T> myQueue = new Queue<T>(); private SemaphoreSlim semaPhore = new SemaphoreSlim(0); public void Enqueue(T t) { lock(myQueue) { myQueue.Enqueue(t); semaPhore.Release(); } } public T Dequeue() { semaPhore.Wait(); lock(myQueue)...

Under what circumstances do you need to synchronize an array in Java?

java,arrays,multithreading,thread-safety
Under what circumstances do you need to synchronize an array? My thoughts are, do you need to synchronize for access? Say two threads access the array at the same time, is that going to crash? What if one edits, while one is reading? (separate values, and the same in different...

Difference between String , StringBuilder & StringBuffer?

java,multithreading,thread-safety
I was just going through the net but I could not find a clear & precise difference between String ,StringBuilder & StringBuffer . Please also explain when should we use them and what do we mean by thread-safe in java ? ...

srand() + rand() with local scope

c++,c++11,random,scope,thread-safety
I have a function that calls srand and rand like this: void foo() { int seed = some_operation(); std::srand(seed); int value = std::rand(); // Do something with random value } However, I don't want to change the global state of rand. Whats the easiest way to get a random number...

is keychain in ios threadsafe?

ios,thread-safety,keychain,keychainitemwrapper
I would like to add some items to the keychain using "secitemadd", but I need to know first, if this is thread safe. I have read the documentation from apple, but I am unable to find anywhere stating if its thread-safe....

NSMutableArray and synchronization

ios,objective-c,thread-safety,nsmutablearray
I am using an NSMutableArray like a Queue. Imagine that the app is like Tinder, and when stack of Cards go below a number I fetch new data. When fetching data, they are added at the end of the NSMutableArray. When swiping, I remove fron object. Should I synchronize these...

Practical Cost of Uncontended Thread Locks

c++,multithreading,performance,thread-safety
For a start, I should place emphasis on _completely uncontended_ thread locks in this subject. I'm well-aware of the very large cost of threads entering highly contended locks, being blocked and suspended and having to wait their turn with context switches and so forth. So I'm not really interested in...

How Instances of immutable types are inherently thread-safe

c#,thread-safety,immutability
I search about Why .NET String is immutable? And got this answer: Instances of immutable types are inherently thread-safe, since no thread can modify it, the risk of a thread modifying it in a way that interfers with another is removed (the reference itself is a different matter). So I...

Are Servlets suitable for composite operations?

java,servlets,thread-safety
Servlets are non-threadsafe, the state could be lost between methods calls by different requests. But can i persist the state between own Servlet's methods during the single request safely to implement composite operations? Like this: public class MyServlet extends HttpServletRequest { private String var; void addH() { var += "h";...

Sharing data between multiple java threads and get the updated value

java,multithreading,thread-safety
I want to create a java application , where we want to make rest calls for multiple users , with the help of an access token. I am using 1 thread per user . The access token, that I am using , is valid for 1 hour.Once the token expires...

Are you there, asynchronously written value?

c#,asynchronous,thread-safety,async-await
The last couple of days I've been reading about async/await. Yesterday I found this video on Channel 9 what made wonder about some things. Please consider the slide below. Aside from the issues Lucian Wischik addresses, I wondered about variable assignment. Say we changed the async void into async Task,...

ncurses in C prints more than it should and prints colour codes

c,thread-safety,ncurses
When I try to print some values in an ncurses window with mvwprintf, it will sometimes print extra characters after what it was expected to print, as if it were reading old memory. This should not happen however, as the value to be printed is strdup-ed beforehand and should only...