Codes on the same thread executed in unusual order - java

This is a piece of code in a SCJP practice question:
public class Threads2 implements Runnable {
public void run() {
System.out.println("run.");
throw new RuntimeException("Problem");
}
public static void main(String[] args) {
Thread t = new Thread(new Threads2());
t.start();
System.out.println("End of method.");
}
}
It was partly mentioned here.
However, my question is not the prior question. As I run the program on a few machines multiple times, I occasionally get RuntimeException before "run" in the output. This does not make sense to me, as these lines of codes executed in the same thread, so it should have been the reverse order.
Can anyone explain why that happens?

e.printStacktrace is using System.err.
System.out and System.err are different object. It has Buffered writer to display to client window.
Even it will execute in different order , it will go to different Buffer.
If Err buffer prints first err will come first.Otherwise out will come first.

Related

Java programming threads and applets

I'm trying to write a java applet program that creates a thread and does two things:
Print numbers in the normal flow of execution
repaint the applet in thread
please take a look at the following code
public class Sample extends applet implements Runnable
{
Thread t=new Thread(this);
int y=500;
public void init()
{
t.start();
for(int i=0;i<30;i++)
{
System.out.print(i);
try {
Thread.sleep(1000);
} catch(Exception e) {}
}
}
public void run()
{
while(true)
{
repaint()
if(y==100) y=500; else y-=100;
}
}
public void paint(Graphics g)
{
g.fillOval(50,y,50,50);
}
}
I wrote this code thinking that a black ball will move up and down and at the same time prints numbers but when i run it it prints numbers and the ball doesn't move until it prints all the numbers. I can't understand why.
You do your printing from the .init() method. Like I said in comments, above, I don't know much about AWT/Swing, and I know even less about the Applet class, but maybe you should do your printing from .start() instead.
The Javadoc says that .init() is called to "inform the applet that it has been loaded," and start() is called "to inform the applet that it should start running."
Like I also said in the comments, above. I would use a timer to drive the animation, and not explicitly create a thread.
I probably would use a timer to drive the counting too: I'd write a .start() method that just starts the two timers and returns.

java program crashes at Scanner initialization

I'm using scanner to read lines from file and replace some text in each line based on given pattern. This is done inside an API. My program is a multithreaded one. At once, more than one thread can call this particular API.
Following is the line scanner initialization line where the thread crashes:
public static void replaceInFile(Properties replacements, Path targetFile) {
...
Scanner in = new Scanner(targetFile, "UTF-8");
...
}
I'm sure no single file will be accessed by two threads at once. Can anyone hint me in the right direction as to what is happening?
UPDATE:
public Void call() throws Exception {
Iterator it = paths.iterator();
while(it.hasNext()){
try {
String filePath = it.next().toString();
//BuildUtil replacer = new BuildUtil();
BuildUtil.replaceInFile(replacements, Paths.get(filePath));
} catch(Exception e) {
e.printStackTrace();
}
}
This is the call() of the thread. Now I observe that it shows "Frame not available" even before stepping into the BuildUtils's replaceInFile method and sometimes after entering in there..I'm not able to figure out what's wrong.. The main thread is exiting I think but I see nothing strange happening here which should make it exit unexpectedly.
I found it. Actually it was my stupidity. I forgot to wait for the threads to exit and so the main thread exited even before threads could complete. Sorry for bothering!
So now I do :
for (int i = 0; i < threadsUsed; i++) {
pool.take().get();
}
for all the threads and shutdown the executor service in finally block

What happened to dead java thread in linux?

I got a NullPointerException in my project and I would like to evaluate what is the sevirity of this issue. The exception is thrown just before the thread finished its task and going to die anyway.
My code failed to catch this excepition, so the thread is dead.
Here is a simple simulation of the situation:
public class Test extends Thread {
public static void main(String[] args) throws InterruptedException {
Test thread = new Test();
thread.start();
while(true) {
System.out.println("I'm still here!");
Thread.sleep(1000);
}
}
public void run() {
String s = null;
int len = s.length(); // causes NullPinterException
}
}
My question is: What is going to happened to this poor thread now? Is its linux file descriptor get freed? Is there any stability or memroy issues that may occur in such kind of code?
The handling is not different than with any other terminated thread. The one thing that happens before is the search for an UncaughtExceptionHandler according to the rules (specific Thread, ThreadGroup, all threads) but apart from this the "normal" cleanup procedure follows. There are no specific consequences regarding sytem resources (depending on the Thread implementation) or memory issues when a thread is terminated by an uncaught exception in contrast to a "normal" termination.
This is not about threads at all. Look at your code:
String s = null;
int len = s.length();
When you are calling s.length() the s is indeed null that causes NullPointerException.
Assign some value to s and you will get its length.

In a multithreaded Java program, does each thread have its own copy of System.out?

I'm writing a multithreaded Java program where each thread potentially needs its standard output redirected to a separate file. Each thread would have its own file. Is it possible to redirect System.out on a "per-thread" basis or are changes to System.out global across all threads?
Is it possible to redirect System.out on a "per-thread" basis
No it is not possible. System.out is static and there is one per JVM that is loaded as part of the system classloader when the JVM initially boots. Although of course using proper logging calls per-thread is recommend, I assume there are reasons why you can't do this. Probably a 3rd party library or other code is what is using System.out in this manner.
One thing you could do (as a radical suggestion) is to make your own PrintStream that delegates to a ThreadLocal<PrintStream>. But you will need to #Override the appropriate methods called by your application to get it to work per-thread.
Lastly, if you are asking this because you are worried about concurrency, System.out is a PrintStream so it is already synchronized under the covers and can be used safely by multiple threads.
Is it possible to redirect System.out on a "per-thread" basis
Some developers from Maia Company have provided a public implementation of a PrintStream that provides one "STDOUT" per thread in this article : "Thread Specific System.out".
In their implementation they override only write methods, flush, close and checkError. It seems to be enough in their case.
They did not "need to #Override all of the methods called to get it to work per-thread" as #Gray stated in his answer.
NOTA:
Please find below the original code from Maia.
I found it here on the wayback machine. The original page was removed from the website of Maia. I reproduce it here for the reader's curiosity. I do not provide any support for this code.
Main.java
Creates a ThreadPrintStream, installs it as System.out, and creates and starts 10 threads.
public class Main {
public static void main(String[] args) {
// Call replaceSystemOut which replaces the
// normal System.out with a ThreadPrintStream.
ThreadPrintStream.replaceSystemOut();
// Create and start 10 different threads. Each thread
// will create its own PrintStream and install it into
// the ThreadPrintStream and then write three messages
// to System.out.
for (int i = 0; i < 10; i++) {
Thread thread = new Thread(new StreamText());
thread.start();
// Report to the console that a new thread was started.
System.out.println("Created and started " + thread.getName());
}
}
}
StreamText.java
A simple Runnable for each thread that opens a file for the thread’s output and installs it into the ThreadPrintStream.
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.PrintStream;
/** A small test class that sets System.out for the currently executing
* thread to a text file and writes three messages to System.out. */
public class StreamText implements Runnable {
#Override
public void run() {
try {
// Create a text file where System.out.println()
// will send its data for this thread.
String name = Thread.currentThread().getName();
FileOutputStream fos = new FileOutputStream(name + ".txt");
// Create a PrintStream that will write to the new file.
PrintStream stream = new PrintStream(new BufferedOutputStream(fos));
// Install the PrintStream to be used as System.out for this thread.
((ThreadPrintStream)System.out).setThreadOut(stream);
// Output three messages to System.out.
System.out.println(name + ": first message");
System.out.println("This is the second message from " + name);
System.out.println(name + ": 3rd message");
// Close System.out for this thread which will
// flush and close this thread's text file.
System.out.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
ThreadPrintStream.java
Extends java.io.PrintStream. An object of ThreadPrintStream replaces the normal System.out and maintains a separate java.io.PrintStream for each thread.
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
/** A ThreadPrintStream replaces the normal System.out and ensures
* that output to System.out goes to a different PrintStream for
* each thread. It does this by using ThreadLocal to maintain a
* PrintStream for each thread. */
public class ThreadPrintStream extends PrintStream {
/** Changes System.out to a ThreadPrintStream which will
* send output to a separate file for each thread. */
public static void replaceSystemOut() {
// Save the existing System.out
PrintStream console = System.out;
// Create a ThreadPrintStream and install it as System.out
ThreadPrintStream threadOut = new ThreadPrintStream();
System.setOut(threadOut);
// Use the original System.out as the current thread's System.out
threadOut.setThreadOut(console);
}
/** Thread specific storage to hold a PrintStream for each thread */
private ThreadLocal<PrintStream> out;
private ThreadPrintStream() {
super(new ByteArrayOutputStream(0));
out = new ThreadLocal<PrintStream>();
}
/** Sets the PrintStream for the currently executing thread. */
public void setThreadOut(PrintStream out) {
this.out.set(out);
}
/** Returns the PrintStream for the currently executing thread. */
public PrintStream getThreadOut() {
return this.out.get();
}
#Override public boolean checkError() {
return getThreadOut().checkError();
}
#Override public void write(byte[] buf, int off, int len) {
getThreadOut().write(buf, off, len);
}
#Override public void write(int b) { getThreadOut().write(b); }
#Override public void flush() { getThreadOut().flush(); }
#Override public void close() { getThreadOut().close(); }
}
You are right but not in the way you think. When a thread uses
System.out.println();
It takes a copy of the reference System.out, but not a copy of the object this references.
This means all threads will normally see the same object for writing to output.
Note: This fields in not thread safe and if you call System.setOut(PrintStream) If you use this there is a potential, undesirable race condition where different threads to have different local copies of System.out. This cannot be used to solve this question.
Is it possible to redirect System.out on a "per-thread" basis
You can do this by replacing System.out with your own implementation which is thread specific. i.e. a sub class of PrintStream. I have done this for logging where I wanted each thread's output to be consistent and not interleaved. e.g. Imagine printing two stack traces in two threads at the same time. ;)
System.out is static, and therefore the same instance is shared between all threads.
Is it possible to redirect System.out on a "per-thread" basis
You can redirect them all to your delegate which will be responsible for 'per-thread' logic.
Here is example of parallel JBehave tests having theirs own file output.

Java console output from another thread dropped

I have a problem with the console output of one of my threads being dropped (in Java). The situation is as follows: I spawn a thread that listens (using a blocking method) for incoming messages. These messages are then asynchronously written to the console. Meanwhile, I read in the user input on the console via System.console().readLine().
The problem is that the text is never written to the console at all. I mean, as the readLine() method is blocking, I would have expected the console at least to show the output that has been written to the console as soon as something is entered in the main thread.. Or am I missing the point here?
The relevant source is
// ...
// handle receiving messages
(new Thread() {
#Override
public void run() {
while (executing) received(new String(subSocket.recv(0)));
}
}).start();
// ...
String input;
try {
while ((input = System.console().readLine()) != null && !input.equals(".")) {
pubSocket.send(input.getBytes(), 0);
Thread.yield();
}
}
catch (Exception ex) { }
finally {executing = false;}
And the received method is
public void received(String s) {
System.console().format("(%s)", s);
System.console().flush();
}
What am I doing wrong? Or is there a better way to do this? I mean, I tried to use a BufferedReader encapsulating the input stream in order to read it linewise and used System.out.format() along with it.. To the same effect - Nothing :(.
Cheers,
fxx
Try something like,
Implement a thread to read from input and store it in synchronized map/vector/list etc..
Another thread is listening on that collection, which will then process the message.
I think this should help in some way... Main thing is, don't run the loop on system input. Give it a try.

Categories

Resources