java,multithreading,concurrency,blocking,executorserviceRelated issues-Collection of common programming errors
Chris R
java exception-handling jni
I’d like a consistent and simple way to throw exceptions in JNI code; something that handles chained exceptions (implicitly from the env->ExceptionOccurred method, or explicitly by parameters, either way is good) and saves me looking up constructors every time I want to do this. All of the above is preferably in C, although I could translate it from C++ at need.Does anyone on SO have something like this that they can share?
morteza
java eclipse sonarqube
i want use sonarqube for analyze a simple java project in eclipse.public class AAA { String kkk=””; }this is test for a simple project analyzingbut after analyze project in eclipse by sonarqube ,i get error:Exception in thread “main” org.sonar.runner.impl.RunnerException: Unable to execute Sonar at org.sonar.runner.impl.BatchLauncher$1.delegateExecution(BatchLauncher.java:91) at org.sonar.runner.impl.BatchLauncher$1.run(BatchLauncher.java:75) at java.security.AccessController.doPrivileged(Nati
Roy08
java android c++ boost tcp
I’m working on a Android app that acts as TCP server/client i want to send data from the app to a server/client that is written in c/c++(made with the boost libraray). I have a normal Java function that calls a native c function for string converstion to bytes:The function is defined as followed (the native function is Convert String:// Send buffer, the method can be used by both client and server objects. public void SendBuffer(String Buffer){try {// Convert char to string to bytebyte[] Temp =
mahen3d
java jvm openfire
I have a unknown error log in my root folder namely hs_err_pidxxx.logInside there i have following i dont know how to fix this or which service is actually doing log. I think its java VM error, i run openfire as a service, which may be the cause, # # There is insufficient memory for the Java Runtime Environment to continue. # Native memory allocation (malloc) failed to allocate 32756 bytes for ChunkPool::allocate # Possible reasons: # The system is out of physical RAM or swap space # In 32 b
xavier.seignard
java arduino native-code nativelibrary
I started to play with arduino an interfacing it with Java, it was pretty straightforward, but now I would like to programmatically load the librxtxSerial native lib, and I can’t figure out. Since I’m on MacOS 64bit and use Java6 I used the following jnilib : http://blog.iharder.net/2009/08/18/rxtx-java-6-and-librxtxserial-jnilib-on-intel-mac-os-x/ as recommended here : http://arduino.cc/playground/Interfacing/JavaAfter that I tried to load it programmatically like this :/*** Loads the jnilib*/
Gray
java jmx apache-camel
I am at Camel 2.9.0. I am able to view the MBean data(routes, processors, etc) for running processes in JConsole.I need to display the same in our user interface. While I try to fetch the attribute values, I get the following error.Note – Attribute “EndpointUri” is fetching the right value.Problem is with “FirstExchangeCompletionTime”. So I am concluding that there might not be any possible problem revolving the server connection. When we were at Camel.1.6.4, the same line of code for the attrib
Miro Markarian
java android gradle newrelic
I have a project that uses the gradle build system and I’m willing to add New Relic monitoring to it. The project (including New Relic) is working fine on Linux (Fedora 20), but won’t build on my Mac development system, and gives out an error stating Agent JAR loaded but agent failed to initialize. Here is the full log of the error:Dev-1:test 0x4d$ ./gradlew clean > Configuring > 1/2 projects > :appobjc[4437]: Class JavaLaunchHelper is implemented in both /Library/Java/JavaVirtualMachin
tyrel
java eclipse sonar
We are running SonarQube 3.7. I’m using the SonarQube plugin for Eclipse, version 3.2.0.20130627-1142, on Eclipse 3.7.2. I have associated my projects with the SonarQube projects and am able to view issues from the server side great. However, if I switch to Local analysis, I get the following error, after CheckStyle, PMD, etc have run:15:16:23.217 INFO – Execute decorators… Exception in thread “main” org.sonar.runner.impl.RunnerException: Unable to execute Sonarat org.sonar.runner.impl.BatchL
Szilagyi Donat
java jdbc methods
First of all sorry for the name of the title, but i dont know how to put another one since english is not my native language.I have the following method to connect to a database:import java.sql.DriverManager; import java.sql.Connection; import java.sql.SQLException;public class PgConnect {public void connect() {Connection connection = null;try {connection = DriverManager.getConnection(“jdbc:postgresql://pgserver:5432/db”, “test”,”test123″);} catch (SQLException e) {System.out.println(“Connectio
BlueDog
java osx ant jni rxtx
I’m using RXTX in my Java application which includes a JNI library. I placed the .jni file in /Libray/Java/Extensions. When I start my application manually via the usual java -jar /path/to/app.jar everything works fine. However when I try to start it via Netbeans or Ant it fails with[java] java.lang.UnsatisfiedLinkError: /Library/Java/Extensions/librxtxSerial.jnilib: no suitable image found. Did find: /Library/Java/Extensions/librxtxSerial.jnilib: no matching architecture in universal wrapper
T.E.D.
multithreading winapi semaphore
I have a question regarding using Semaphores HANDLE WINAPI CreateSemaphore(…);Is there anyway I can get the current value of the semaphore?
gtech
ruby multithreading
I’m using ruby-head and Debian wheezy x64. When I run a multithreaded ruby script, htop shows that it’s using multiple cores visually with the bars at the top, and that it’s using 100% CPU on the process list but it’s only using 100% of the capacity of one core. I assume it’s possible to have multiple cores running at 100% and this number seems too convenient to be bottle-necked by either the program logic or another hardware aspect. Is the OS limiting the amount of available instructions I’m us
babay
android multithreading exception
Google play reports an exception on some devices (all are “other” and one “LG-E400”, so it might be some custom android build)Exception is:java.lang.IllegalArgumentException at android.os.StatFs.native_setup(Native Method) at android.os.StatFs.<init>(StatFs.java:32) at android.webkit.CacheManager.init(CacheManager.java:199) at android.webkit.BrowserFrame.<init>(BrowserFrame.java:210) at android.webkit.WebViewCore.initialize(WebViewCore.java:201) at android.webkit.WebViewCore.access$5
Wyatt Anderson
javascript c++ multithreading internet-explorer com
I’m trying to make 2 different browsers communicate with each other through native code host (C++) using JS window.external.The syntax is something like: on destination.js:window.external.register(“dest”, eventCallbak); function eventCallback(senderID, data) { alert(“message recieved from ” + senderID + ” with data of ” + data); }on source.js:window.external.sendMsg(“source”, “dest”, “Hello dest! this is source…”);I’ve managed to do so synchronously, by saving the eventCallback parameter
GeeKay
java multithreading profiler jconsole jstack
I am trying to profile my java application running on eclipse using ‘jconsole’. But i am unable to do so and i get the following exception Exception in thread “VMPanel.connect” java.lang.InternalError: Remote thread failed for unknown reasonat sun.tools.attach.WindowsVirtualMachine.enqueue(Native Method)at sun.tools.attach.WindowsVirtualMachine.execute(WindowsVirtualMachine.java:96)at sun.tools.attach.HotSpotVirtualMachine.executeCommand(HotSpotVirtualMachine.java:217)at sun.tools.attach.HotSpot
talhamalik22
java android multithreading audio android-ndk
I am trying to use a java sound modulation library for android i.e sonic. I am trying to run its sample android application but it is giving me exception saying “exception in Initialize error” i cannot figure out the cause. following is the code kindly check.public class SonicTest extends Activity { static Sonic sonic; @Override public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState); setContentView(R.layout.main); }public void play(View view) {
Wumpus Q. Wumbley
multithreading winapi strawberry-perl chdir file-attributes
I used File::Find to traverse a directory tree and Win32::File’s GetAttributes function to look at the attributes of files found in it. This worked in a single-threaded program.Then I moved the directory traversal into a separate thread, and it stopped working. GetAttributes failed on every file with “The system cannot find the file specified” as the error message in $^E.I traced the problem to the fact that File::Find uses chdir, and apparently GetAttributes doesn’t use the current directory. I
Gnijuohz
c multithreading gui gtk
I wrote a C/S application using udp and it keeps giving me errors, which I believe has something to do with the way I use threads.When the client program starts, it first initializes a login window and starts a new thread to listen to the response from the server. After it submits user name and password, the new thread will receive a message indicating whether it submitted the right info. If it did, then the thread would initializes the main GUI window. But it would give strange errors:Fatal IO
Molloch
.net multithreading printing thread-safety
I am not sure if this is to with a threading issue or not.I am printing labels to a standard windows printer. The label is drawn in GDI and then passed to another object which prints it on a background thread.I am using a BackgroundWorker for this process. LabelPrinter.Print(Label as PrintLabel) starts the backgroundWorker and passes the label details to it. The PrintPage eventhandler renders the page and sends it to the printer.The issue is, users occasionally get an error stating:System.Drawin
Vegar Westerlund
python multithreading scheduling
I’m using python to interface a hardware usb sniffer device with the python API provided by the vendor and I’m trying to read (usb packets) from the device in a separate thread in an infinite loop (which works fine). The problem is that my main loop does not seem to ever get scheduled again (my read loop gets all the attention).The code looks much like this:from threading import Thread import time usb_device = 0def usb_dump(usb_device):while True:#time.sleep(0.001)packet = ReadUSBDevice(usb_devi
BeeOnRope
java debugging concurrency stack-trace jvm-hotspot
If you get the stack dump of a process, e.g., via jstack, you get information about locked monitors (and synchronizers) with an address for each. E.g., from a trivially deadlocked two-thread process (using jstack):”Thread-0″ prio=10 tid=0x00007f1444042000 nid=0x2818 waiting for monitor entry [0x00007f14433ca000]java.lang.Thread.State: BLOCKED (on object monitor)at scrap.DeadlockTest$Deadlocker.run(DeadlockTest.java:49)- waiting to lock <0x00000007c14e6378> (a java.lang.Object)- locked <
Gilles
java multithreading concurrency native jna
For an existing java application (which I do not have the source code) I am developing a plug-in which is calls a shared library. Unfortunately this shared library (written in C) is not thread safe. The application is calling my plugin within several concurrent threads hence the shared library is called by these concurrent threads and naturally it gives many errors due to concurrency ( e.g: already open files are prevented from being opened etc)I am accessing the shared library via JNA. I even h
Arkanon
java concurrency thread-safety stringbuilder stringbuffer
I know the difference between StringBuffer and StringBuilder. read here!And generally, as the javadoc says, Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.But, the javadoc of StringBuilder also says:Instances of StringBuilder are not safe for use by multiple threads. If such synchronization is required then it is recommended that {@link java.lang.StringBuffer} be usedSo, I am wondering, is the case that Stri
rmarimon
java multithreading concurrency
I would like to create a class that runs something (a runnable) at regular intervals but that can be awaken when needed. If I could encapsulate the whole thing I would like to expose the following methods:public class SomeService implements Runnable {public run() {// the code to run at every interval}public static void start() { }public static void wakeup() { }public static void shutdown() { }}Somehow I’ve gotten this far. But I’m not sure if this is the correct approach.public class SomeServi
Whistler
asp.net-mvc-3 concurrency timestamp
I building my first MVC project and having problem with handling concurrency. Web application was working fine (adding, editing and deleting) before I decided to add concurrency handling.//Entity class Line public class Line {[Key][Required(ErrorMessage = “Please enter a line name”)]public string Name { get; set; }[Required(ErrorMessage = “Please enter a Business Unit name”)]public string BU { get; set; }[Required(ErrorMessage = “Please enter a Department name”)]public string Department { get; s
Bevor
android concurrency android-asynctask runtimeexception
I have an AsyncTask which does a lot of JSON calculations. public class InitializationTask extends AsyncTask<Void, Void, InitializationResult> {private ProcessController processController = new ProcessController();private ProgressDialog progressDialog;private MainActivity mainActivity;public InitializationTask(MainActivity mainActivity) {this.mainActivity = mainActivity;}@Overrideprotected void onPreExecute() {super.onPreExecute();progressDialog = new ProgressDialog(mainActivity);progressD
sooprise
c# linq concurrency
I understand how editing rows can cause concurrency issues, but concurrency issues being caused by selecting rows is something I do not understand. If a query selects data from a database, how can a concurrency issue arise? Is it if there is a change made to the data I’m selecting, things will blow up?In any case, if there is a concurrency issue caused by a select query, what is the best way to handle it? This is what I have in mind, but I wouldn’t be surprised at all if it were wrong. try {va
Christian Fries
java concurrency parallel-processing stream java-8
Consider the following situation: We are using a Java 8 parallel stream to perform a parallel forEach loop, e.g., IntStream.range(0,20).parallel().forEach(i -> { /* work done here */})The number of parallel threads is controlled by the system property “java.util.concurrent.ForkJoinPool.common.parallelism” and usually equal to the number of processors.Now assume that we like to limit the number of parallel executions for a specific piece of work – e.g. because that part is memory intensive and
Reusable
java concurrency concurrenthashmap
I have a stateless Java application deployed to a tomcat web server. Due to the nature of the data, at any given time, all http thread has to process for different key (in other words: all threads must be processing different key). Hence, i wrote a module that queue the http post if the key of the request is current in progress (by a http post before this). I will only continue to process the current http post once the previous http post with the same key has complete its process. I have wrote
clime
concurrency lamp
Before I have started to do web-programming I had thought it was easy. Now, after a year of experience I think it can be really damn hard mainly because of concurrency issues.Because that was some very unexpected finding out, I tried to ask my more experienced friends (they had made some apps like e-shops etc.) about it. Specifically, I asked them if you can really have concurrency issues that you need to solve or otherwise you are at danger of your data becoming inconsistent and they were like:
K. Brafford
python console keyboard blocking nonblocking
How can I poll the keyboard from a console python app? Specifically, I would like to do something akin to this in the midst of a lot of other I/O activities (socket selects, serial port access, etc.):while 1:# doing amazing pythonic embedded stuff# …# periodically do a non-blocking check to see if# we are being told to do something elsex = keyboard.read(1000, timeout = 0)if len(x):# ok, some key got pressed# do somethingWhat is the correct pythonic way to do this on Windows? Also, portabilit
Teddy
javascript html blocking
How do I prevent JavaScript from blocking other JavaScript’s from starting to download?I have the following on my web site:<html> <body> …. <script type=”text/javascript” src=”http://example.com/ex.js”></script> <script type=”text/javascript” src=”http://google.com/google-maps.js”></script> </body> </html>When I use the YSlow Firefox add-on, I can see from the network traffic tab that the google.com/google-maps.js JavaScript won’t start downloadi
Duncan
java multithreading testing concurrency blocking
According to book Java Concurrency in Practice at Listing 12.3 we could test a concurrent code using the following sample code:void testTakeBlocksWhenEmpty() {final BoundedBuffer<Integer> bb = new BoundedBuffer<Integer>(10);Thread taker = new Thread() {public void run() {try {int unused = bb.take();fail(); // if we get here, it’s an error} catch (InterruptedException success) { }}};try {taker.start();Thread.sleep(LOCKUP_DETECT_TIMEOUT);taker.interrupt();taker.join(LOCKUP_DETECT_TIMEO
MRalwasser
java multithreading scheduled-tasks task blocking
I’d like to utilize some lightweight task management (e.g. ScheduledThreadPoolExecutor) for periodically doing some Tasks which might block (e.g. because of waiting to acquire a monitor/lock). In such case the task management should detect that situation and should spawn another task/thread of the same kind which blocks. How can this be achieved?And as a bonus question: Documentation of ScheduledThreadPoolExecuter states that “If any execution of the task encounters an exception, subsequent exe
Josh Caswell
objective-c cocoa locking blocking grand-central-dispatch
I need to protect a critical area of my code, which is multi-threaded. I want to prevent it from being called multiple times before the other thread is finished. This is what I am working with:- (void) filterAllEventsIntoDictionary{// start critical areaif (self.sortedKeys.count != 0) {[self.sortedKeys removeAllObjects];}dispatch_async(self.filterMainQueue, ^{[self internal_filterAllEventsIntoDictionary]; dispatch_sync(dispatch_get_main_queue(), ^{[self.tableView reloadData];});}); }Since the in
pandre
blackberry blocking blackberry-simulator
I have a Blackberry application which, when run in some emulators with touch support (ex: 9500, 9520, 9530, 9550), terminates with: “Application is not responding; process XPTO terminated”Using logs, I found out that it seems like the application is stopping in a class where I asynchronously make HTTP requests: something like: public class LoadingFullScreen extends FullScreen implements Runnable {private Thread actionThread = null;protected void onDisplay() {actionThread = new Thread(this);acti
tomasK
scripting powershell blocking
I have this simple script:$files = dir .\configs | ? { !$_.PSIsContainer }foreach($file in $files) {try{.\MyApp.exe -ErrorAction Stop $file}catch{write-host “!!!!!!!!!!!!error!!!!!!!!!!!!!!”continue} }The problem is that when .\MyApp.exe -ErrorAction Stop $filecrash, the windows message box about application crash appear and my script block, catch is not hit and only way to continue is click Storno button in the message box.So how to prevent blocking?
Javier J. Salmeron Garcia
ipc named-pipes blocking nonblocking
I am writing a bash program that has IPC between two proccesses (A and B) via named pipes. I am worried because if A crashes, B may be blocked indefinitely (and vice versa), because named pipes are blocking. Can I link A and B so, if A crashes, force B to crash too? Any other alternatives to solve this blocking problem would be appreciated. Thank you in advance.
Saif Bechan
iptables port blocking
I have a web server running pleks and get attacked a lot every day. I configured a firewall, and there are some predefined services such as www, and ftp, etc.I am planning to block all the ports except for the www port and the PLESK port. When I need ftp or ssh access for example i will open the ports in PLESK and then start to work.Is this a good thing to do or are there some downsides on doing this.There are some ports I am not sure of, such as SMTP,POP3,IMAP, DNS. Can i close these ports or i
jimg
debian blocking linux-kernel
Been getting these runaway conditions on a lightly loaded vps (debian squeeze kernel 2.6.38-bpo.2-amd64, 2GB, SSD) – top load is nothing , then jumps to 30.0 & everything grinds to a halt. I’m guessing the Xen Hypervisor kicks in and limits things – vendor control panel shows cpu @ 175%. A few minutes will pass, cpu & load will fall back to nominal levels and things return to normal.Here is a copy of the latest kern.logOct 11 20:10:34 stage kernel: [348092.046302] Clocksource tsc unstab
Phate
java executorservice
In my app I need to execute different future task. My call would be something likepublic Item getTaskResult(){//creating the task object named taskExecutors.newCachedThreadPool().execute(task);…. }Is it wrong to just call Executors.newCachedThreadPool() ? Should I keep a reference to it? Am I wasting some resources doing in my way?
Oxford
java multithreading concurrency producer-consumer executorservice
public class MainClass {private static final int size = 5;private ExecutorService prodExec = Executors.newFixedThreadPool(size); private ExecutorService consExec = Executors.newFixedThreadPool(size);//main method herepublic void start(String[] args) {for (int index = 0; index < size; index++) {Runnable producer = new Producer(consExec, listOfIds);prodExec.execute(producer);}Runtime.getRuntime().addShutdownHook(new Thread() {public void run() {prodExec.shutdown();try {prodExec.awaitTermination
AndreasEK
osgi classloader executorservice jbehave rft
I am struggling with a situation in which a ClassLoader is trying to resolve a resource, which only works under certain conditions. The use-case is as follows: I am using IBM Rational Functional Tester in combination with JBehave for automated acceptance tests. JBehave specifies the tests as plain text story files. These story files can refer to other story files, so called “Given Stories”. JBehave uses the ExecutorService to execute stories potentially multi-threaded. While JBehave has no probl
blue-sky
java multithreading junit executorservice
In below test class just “before” is outputted.But if I removed Thread.sleep the following is outputted : before after before after before after before after before after before after before after before after before after before afterWhich is what I expect.When I use Thread.sleep I think that there should be a 1000ms delay between each output of before afterWhy is this not occuring & how can the code be amended so that the generated output is same regardless of calling sleep or not ?import
plastilino
java concurrency threadpool deadlock executorservice
I found an unexpected deadlock while running tasks in a ThreadPoolExecutor.The idea is a main task that launches a secondary task that changes a flag. The main task halts until the secondary task updates the flag.If corePoolSize >=2 the main task completes as expected. If corePoolSize <2 it seems that the secondary task is enquenqued but never launched. Using a SynchronousQueue instead, the main task completes even for corePoolSize=0.I’d like to know:what’s the cause of the deadlock?. It seem
assylias
java executorservice future executionexception
I have a method that performs some task with a timeout. I use the ExecutorServer.submit() to get a Future object, and then I call future.get() with a timeout. This is working fine, but my question is the best way to handle checked exceptions that can be thrown by my task. The following code works, and preserves the checked exceptions, but it seems extremely clumsy and prone to break if the list of checked exceptions in the method signature changes.Any suggestions on how to fix this? I need to ta
Anupam Saini
java executorservice
I have a very long running task that periodically polls a web service for XML content. I am using a Scheduled executor for these periodic runs and everything works fine.The JavaDoc of ScheduledExecutorService scheduleAtFixedRate state that … If any execution of the task encounters an exception, subsequent executions are suppressed …*This clearly implies that in case of unhandled exceptions, The application even though running , is effectively in a stopped state and doing nothing. I want to e
Maian
java multithreading concurrency executorservice dataflow
EDIT: This is basically a “how to properly implement a data flow engine in Java” question, and I feel this cannot be adequately answered in a single answer (it’s like asking, “how to properly implement an ORM layer” and getting someone to write out the details of Hibernate or something), so consider this question “closed”.Is there an elegant way to model a dynamic dataflow in Java? By dataflow, I mean there are various types of tasks, and these tasks can be “connected” arbitrarily, such that whe
neevek
java concurrency executorservice
I have tried many different ways to immediately stop a task which is started using an ExecutorService, with no luck.Future<Void> future = executorService.submit(new Callable<Void>(public Void call () {… do many other things here..if(Thread.currentThread.isInterrupted()) {return null;}… do many other things here..if(Thread.currentThread.isInterrupted()) {return null;}} ));if(flag) { // may be true and directly cancel the taskfuture.cancel(true); }Sometimes I need to cancel the tas
Gray
java multithreading exception executorservice
I’m trying to use Java’s ThreadPoolExecutor class to run a large number of heavy weight tasks with a fixed number of threads. Each of the tasks has many places during which it may fail due to exceptions.I’ve subclassed ThreadPoolExecutor and I’ve overridden the “afterExecute” method which is supposed to provide any uncaught exceptions encountered while running a task. However, I can’t seem to make it work.For example:public class ThreadPoolErrors extends ThreadPoolExecutor {public ThreadPoolErro
Web site is in building
I discovery a place to host code、demo、 blog and websites.
Site access is fast but not money