I'm coming from VB6 and I'm new to Java. In VB6, DoEvents gives up the processor and allows it to process other threads. Is there a similar thing in Java? How do I use it?
gives up the processor and allows it to process other threads.
Thread#yield() is the java counterpart to relinquish the control of the processors voluntarily.
From the javadoc for java.lang.Thread#yield():
A hint to the scheduler that the current thread is willing to yield its current use of a processor. The scheduler is free to ignore this hint.
Yield is a heuristic attempt to improve relative progression between threads that would otherwise over-utilise a CPU. Its use should be combined with detailed profiling and benchmarking to ensure that it actually has the desired effect.
It is rarely appropriate to use this method. It may be useful for debugging or testing purposes, where it may help to reproduce bugs due to race conditions. It may also be useful when designing concurrency control constructs such as the ones in the java.util.concurrent.locks package.
Note:
In case of Java based desktop UI frameworks like Swing, RIM's UI application, there are ways to modify the UI using invokeLater() type of semantics.
Having moved from VB6 to Java myself and having searched for an answer to this very same question at the time, I can tell you that I had to change my way of thinking about how to do things. The need for "doEvents" is most likely due to you attempting to write a Java program in the same way you wrote VB6 or an attempt to port a VB6 project "line by line" to Java. Neither is a good idea. Take a good look at the swing tutorial (if this is about UI) and the threading tutorial whether it is UI or not. Pay a close attention to and try to understand how the Event Dispatch thread works. I found the Java tutorials to be a great starting place, they are now located at Oracle: http://docs.oracle.com/javase/tutorial/ look at the samples and read the code, they are a good place to learn/experiment
You need to start thinking in Java and not translate VB6 to Java, it took me a while to get there but not too long and overcoming the need for "doEvents" will take you a long way down that path if you understand the way around it. Good luck, and welcome to Stackoverflow, this is a great place to look for help!
Related
I'd like to add groovy-shell-server to our application. We have run into a couple production issues recently where a call to an internal API could have expedited diagnosis or even provided a short-term fix. Groovy-shell-server provides a nice way to achieve this.
But actually using this in production introduces a potential complication. Let's say that, despite careful peer review, we execute a script which pegs the CPU, or gets stuck in an endless loop. I need some way to kill that thread, pronto! So I was thinking about enhancing groovy-shell-server to support an optional hard stop() of a running Groovy client thread.
I know that Thread.stop() is inherently unsafe; it's been discussed on StackOverflow before. My question is, do you think the benefits might outweigh the risks in this case? Is using Thread.stop() a pragmatic choice as a kind of "emergency brake" for a runaway GroovyShell server thread? Or the likelihood of leaving objects in an inconsistent state is too high?
(Alternately, if someone has a better way to provide programmatic, interruptible access to a running java application, I'm all ears.)
I think that generally is it bad to use deprecated API and specifically it is not recommended to use Thread.stop().
BUT there is not rule without exception. I think this is the case. According to my experience Thread.stop() works and really stops thread. I used it many years ago in applet that was targeted for Netscape. Some of its versions did not support Thread.interrupt() well.
The only alternative solution I can think about is using separate process. But in this case you have to implement some process-to-process transport for data transfer. I do not know details of your task but usually the price is too high.
So, if I were you I'd use Thread.stop() with very big apologize comment.
I make a tool and provide an API for external world, but I am not sure whether it is thread safe. Because users may want t use it in multiple-thread environment. Is there any way or tool that I can use to verify whether my API is thread safe in Java?
No. There is no such tool. Proving that a complex program is thread safe is very hard.
You have to analyze your program very carefully to ensure that is thread safe. Consider buying "Java concurrency in practice" (very good explanation of concurrency in java).
Stress tests, or static analysis tools like PMD and FindBugs can uncover some concurrency bugs in your code. So these can show if your code is not thread-safe. However they can never prove if it is thread-safe.
The most effective method is a thorough code review by developer(s) experienced in concurrency.
You can always stress-test it with tools like jmeter.
But the main problem with threads is that they're mostly unpredictable, so even with stress-tests etc. you can't be 100% sure that it will be totally thread safe.
Resources :
Wikipedia - Thread-safety
This is a variant (or so called "reduction") of the Halting Problem. Therefore it is provably unsolvable. for all non-trivial cases. (Yes, that's an edit)
That means you can find errors by any usual means (statistics, logic) but you can never completely prove that there are none.
I suppose those people saying proving an arbitrary multithreaded program is thread-safe is impossible are, in a way, correct. An arbitrary multithreaded program, coded without following strict guidelines, simply will have threading bugs, and you can't validly prove something that isn't true.
The trick is not to write an arbitrary program, but one with threading logic simple enough to possibly be correct. This then can be unambiguously validated by a tool.
The best such tool I'm aware of is CheckThread. It works on the basis of either annotations, or xml config files. If you mark a method as '#ThreadSafe' and it isn't, then you get a compile-time error. This is checked by looking at the byte code for thread-unsafe operations, e.g. reads/write sequences on unsynchronised data fields.
It also handles those APIs that require methods to be called on specific threads, e.g. Swing.
It doesn't actually handle deadlocks, but those can be statically eliminated without even requiring annotation, by using a tool such as Jlint. You just need to follow some minimal standards like ensuring locks are acquired according to a DAG, not willy-nilly.
You cannot and never will be able to automatically proof that a program is threadsafe anymore that you can prove that a program is correct (unless you think you solved the halting program, which you didn't).
So, no, you cannot verify that an API is threadsafe.
However in quite some case you can prove that it is broken, which is great!
You may also be interested in automatic deadlock detection, which in quite some case simply "just work". I'm shipping a Java program on hundreds of desktops with such a deadlock detector installed and it is a wonderful tool. For example:
http://www.javaspecialists.eu/archive/Issue130.html
You can also stress test your application in various ways.
Bogus multi-threaded programs tend to not work very well when a high load is present on the system.
Here's a question I asked about how to create easily create a high CPU load on a Un*x system, for example:
Bash: easy way to put a configurable load on a system?
I'm doing some routine in Java (1.5)+Swing, that damands some time. How the best way to implement this routing outside the swing thread, to avoid UI freezing?
Thanks in advance
At first blush, look at the SwingWorker class. When you want to make the code more robust and testable, you probably want to move away from that, but it is a good enough first start.
You can get a version for Java 1.5 here. With 1.6 it is part of the standard API.
Using SwingWorker is of course good idea and I recommend that. Also writing custom javax.swing.Timers and java.lang.Threads .
But don't forget to use profiler - it can help you to find many problems. Like Swing is often having trouble with "dead" Listeners holding some references which can not be garbage collected (resulting in very slow responses or freezing of UI or even memory leaks). Profiler will help you to investigate memory needs of specific situations when using your application and therefore you might be able to do fine tuning of your app.
Resolved as comment:
"This could help: stackoverflow.com/questions/2564388/javas-swing-threading – Andreas_D Jul 5 at 22:01"
I'm just starting with J2ME and lcdui, and I'm looking at some sample code that calls methods on lcdui objects from a worker thread.
In my experience with desktop GUI toolkits, this is usually forbidden - is lcdui different? Is it really OK to do this?
(I've Googled for an answer to this question but not found anything - a link to a defintive answer in some official documentation would be excellent!)
LCDUI is a bit of a funny one, what you can and can't do often depends on the implementation. I've written apps for BlackBerry that don't have a problem with accessing UI objects from a background thread (except the usual threading problems that you create yourself), but I'm pretty sure some other platforms will forbid this.
If you're concerned about this, or it's causing you issues, you might want to look at using javax.microedition.lcdui.Display.callSerially(Runnable). This executes the given Runnable object in the UI thread (if there is such a thing in LCDUI) and serializes it with other UI events and paint operations. You can read more about it in the J2ME API docs.
Using the javax.microedition.lcdui classes, thread-safety is supposedly one of the goals of the UI classes according to the Concurrency section of this documentation. As Rory indicated, it is entirely possible that different vendors implemented this as more of a "suggestion" rather than a rule.
At one time, I was looking for similar information, but was also unable to find the magic phrasing to offer Google to get good results.
Best of luck!
I am working on a servlet (runs on tomcat) which receives requests that contains Java Script code, and using the java scripting API framework evaluates/run the code and returns the answer to the user.
Since we are dealing with user generated code, the code can be a good code and it can be bad code. As an example for a bad code can be while(true); which will endlessly loop in the server taking unnecessary resources
my questions
1) how can i discover a bad code?
2) once identified as a bad/malicious code what is the best way to stop the run?
thanks
My question to you: what counts as bad code?
If you cannot come up with a formal definition of what counts as bad code, you cannot hope to be able to detect it. And since this is probably what your question really meant, I'll put forward my answer - there's no way to do it.
Even a seemingly trivial thing such as whether a program will terminate or not cannot be determined ahead of time, and I'd expect any definition of bad code would be something that couldn't terminate.
Thus to my mind you have one major option: trust your users (or alternatively don't trust them and don't run anything).
Something that might work otherwise is to run the script in a strict sandbox, and terminate it after an appropriate amount of time if it hasn't already finished running. It very much depends on your circumstances as to what is acceptable.
You are really jumping down the rabbit hole on this one. There is no way to determine in advance if code is resource intensive or has mailious intent. Even humans have a hard time with that. Having said that there are some things you can do to defend yourself.
Use Rhino instead of Java 6's built-in JS scripting engine as it gives you more options.
Implement a custom context that monitors instruction count. This gives you an opportunity to interrupt scripts that are infinitely looping. See Rhino's ContextFactory class
run your scripts in a separate thread so that you can interrupt scripts stuck in in wait states that don't trigger the Context's intruction count
Implement a security manager: see Overview, API. This will allow you to restrict the script to just those objects it should be interacting with.
I have implemented 1,2, and 3 in Myna and you are welcome to steal code
There's already a tool that identifies 'bad' JavaScript, JSLint. Obviously the definition of bad code is highly subjective, but JSLint provides a wide range of options, so you should be able to configure it to conform fairly closely to your definition of bad.
You can submit code (and configuration options) to JSLint via the web form linked to above. It should also be possible to submit code (and options) to JSLint programatically, but you should get the author's permission if you plan to do this regularly.