Might I ask here for a piece of advice.
I am creating several threads in the constructor of my class as I had a performance issue as I would like to add on more of series and flows. However those threads takes random time to initialize which means the code still execute and putting aside the order of my array list is now messed up, it is not fully loaded when the code keeps executing.
Series is a wrapper which add listeners and to simplify output a series of ArrayList that my frame needs to instantiate a chart in a panel.
what is the correct way to proceed here. I feel I do it all wrong.
new Thread(new Runnable() {
public void run() {
Flow flow = new Flow(idThread, 1);
flows.add(flow);
series.add(new Series(3000, ProcessingType.NONE, flow, controller));
series.add(new Series(5000, ProcessingType.FILTER, flow, controller));
}
}).start();
new Thread(new Runnable() {
public void run() {
Flow flow = new Flow(idThread, 2);
flows.add(flow);
series.add(new Series(4000, ProcessingType.NONE, flow, controller));
series.add(new Series(5000, ProcessingType.FILTER, flow, controller));
}
}).start();
Global.getInstance().mySeries(idThread, series);
trading = new Trading(idThread);
I try naively a
while (series.size()<10){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
However "logically" the main thread should sleep and allow time for the other ones to initialize?
Thanks
Don't extend Thread, implement Runnable. Don't start new threads from within a constructor unless you really like weird bugs. You can use various synchronization idioms such as https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CountDownLatch.html to "line the horses up at the gate before the race".
You can use a CyclicBarrier, where you can call await() method in main, until all you thread have reached this barrier your main thread will wait.
http://tutorials.jenkov.com/java-util-concurrent/cyclicbarrier.html
Related
Java Concurrency In Practice, 12.1.2. Testing Blocking Operations:
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_TIMEOUT);
assertFalse(taker.isAlive());
} catch (Exception unexpected) {
fail();
}
}
This is one of the few cases in which it is appropriate to subclass
Thread explicitly instead of using a Runnable in a pool: in order to
test proper termination with join. The same approach can be used to
test that the taker thread unblocks after an element is placed in the
queue by the main thread.
But I don't see how extending Thread helps with testing that. For me it seems that the same test could be done with passing Runnable to Thread. Can somebody explain that?
This is one of the few cases in which it is appropriate to subclass
Thread explicitly instead of using a Runnable in a pool: in order to
test proper termination with join.
In other words that approach lets you a chance to interrupt the test thread and join it to make sure it has been terminated properly. You can't handle threads in that way if you use, for example - ThreadPoolExecutor class.
Also, it is OK to create a new thread, initiating it with Runnable, like Thread taker = new Thread(() -> {...});. Remember that the book was written about 8 years ago, and creating Runnable instead of subclass of Thread would make that example a bit longer.
I have a method that I would like to call. However, I'm looking for a clean, simple way to kill it or force it to return if it is taking too long to execute.
I'm using Java.
to illustrate:
logger.info("sequentially executing all batches...");
for (TestExecutor executor : builder.getExecutors()) {
logger.info("executing batch...");
executor.execute();
}
I figure the TestExecutor class should implement Callable and continue in that direction.
But all i want to be able to do is stop executor.execute() if it's taking too long.
Suggestions...?
EDIT
Many of the suggestions received assume that the method being executed that takes a long time contains some kind of loop and that a variable could periodically be checked.
However, this is not the case. So something that won't necessarily be clean and that will just stop the execution whereever it is is acceptable.
You should take a look at these classes :
FutureTask, Callable, Executors
Here is an example :
public class TimeoutExample {
public static Object myMethod() {
// does your thing and taking a long time to execute
return someResult;
}
public static void main(final String[] args) {
Callable<Object> callable = new Callable<Object>() {
public Object call() throws Exception {
return myMethod();
}
};
ExecutorService executorService = Executors.newCachedThreadPool();
Future<Object> task = executorService.submit(callable);
try {
// ok, wait for 30 seconds max
Object result = task.get(30, TimeUnit.SECONDS);
System.out.println("Finished with result: " + result);
} catch (ExecutionException e) {
throw new RuntimeException(e);
} catch (TimeoutException e) {
System.out.println("timeout...");
} catch (InterruptedException e) {
System.out.println("interrupted");
}
}
}
Java's interruption mechanism is intended for this kind of scenario. If the method that you wish to abort is executing a loop, just have it check the thread's interrupted status on every iteration. If it's interrupted, throw an InterruptedException.
Then, when you want to abort, you just have to invoke interrupt on the appropriate thread.
Alternatively, you can use the approach Sun suggest as an alternative to the deprecated stop method. This doesn't involve throwing any exceptions, the method would just return normally.
I'm assuming the use of multiple threads in the following statements.
I've done some reading in this area and most authors say that it's a bad idea to kill another thread.
If the function that you want to kill can be designed to periodically check a variable or synchronization primitive, and then terminate cleanly if that variable or synchronization primitive is set, that would be pretty clean. Then some sort of monitor thread can sleep for a number of milliseconds and then set the variable or synchronization primitive.
Really, you can't... The only way to do it is to either use thread.stop, agree on a 'cooperative' method (e.g. occassionally check for Thread.isInterrupted or call a method which throws an InterruptedException, e.g. Thread.sleep()), or somehow invoke the method in another JVM entirely.
For certain kinds of tests, calling stop() is okay, but it will probably damage the state of your test suite, so you'll have to relaunch the JVM after each call to stop() if you want to avoid interaction effects.
For a good description of how to implement the cooperative approach, check out Sun's FAQ on the deprecated Thread methods.
For an example of this approach in real life, Eclipse RCP's Job API's 'IProgressMonitor' object allows some management service to signal sub-processes (via the 'cancel' method) that they should stop. Of course, that relies on the methods to actually check the isCancelled method regularly, which they often fail to do.
A hybrid approach might be to ask the thread nicely with interrupt, then insist a couple of seconds later with stop. Again, you shouldn't use stop in production code, but it might be fine in this case, esp. if you exit the JVM soon after.
To test this approach, I wrote a simple harness, which takes a runnable and tries to execute it. Feel free to comment/edit.
public void testStop(Runnable r) {
Thread t = new Thread(r);
t.start();
try {
t.join(2000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
if (!t.isAlive()) {
System.err.println("Finished on time.");
return;
}
try {
t.interrupt();
t.join(2000);
if (!t.isAlive()) {
System.err.println("cooperative stop");
return;
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.err.println("non-cooperative stop");
StackTraceElement[] trace = Thread.getAllStackTraces().get(t);
if (null != trace) {
Throwable temp = new Throwable();
temp.setStackTrace(trace);
temp.printStackTrace();
}
t.stop();
System.err.println("stopped non-cooperative thread");
}
To test it, I wrote two competing infinite loops, one cooperative, and one that never checks its thread's interrupted bit.
public void cooperative() {
try {
for (;;) {
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.err.println("cooperative() interrupted");
} finally {
System.err.println("cooperative() finally");
}
}
public void noncooperative() {
try {
for (;;) {
Thread.yield();
}
} finally {
System.err.println("noncooperative() finally");
}
}
Finally, I wrote the tests (JUnit 4) to exercise them:
#Test
public void testStopCooperative() {
testStop(new Runnable() {
#Override
public void run() {
cooperative();
}
});
}
#Test
public void testStopNoncooperative() {
testStop(new Runnable() {
#Override
public void run() {
noncooperative();
}
});
}
I had never used Thread.stop() before, so I was unaware of its operation. It works by throwing a ThreadDeath object from whereever the target thread is currently running. This extends Error. So, while it doesn't always work cleanly, it will usually leave simple programs with a fairly reasonable program state. For example, any finally blocks are called. If you wanted to be a real jerk, you could catch ThreadDeath (or Error), and keep running, anyway!
If nothing else, this really makes me wish more code followed the IProgressMonitor approach - adding another parameter to methods that might take a while, and encouraging the implementor of the method to occasionally poll the Monitor object to see if the user wants the system to give up. I'll try to follow this pattern in the future, especially methods that might be interactive. Of course, you don't necessarily know in advance which methods will be used this way, but that is what Profilers are for, I guess.
As for the 'start another JVM entirely' method, that will take more work. I don't know if anyone has written a delegating class loader, or if one is included in the JVM, but that would be required for this approach.
Nobody answered it directly, so here's the closest thing i can give you in a short amount of psuedo code:
wrap the method in a runnable/callable. The method itself is going to have to check for interrupted status if you want it to stop (for example, if this method is a loop, inside the loop check for Thread.currentThread().isInterrupted and if so, stop the loop (don't check on every iteration though, or you'll just slow stuff down.
in the wrapping method, use thread.join(timeout) to wait the time you want to let the method run. or, inside a loop there, call join repeatedly with a smaller timeout if you need to do other things while waiting. if the method doesn't finish, after joining, use the above recommendations for aborting fast/clean.
so code wise, old code:
void myMethod()
{
methodTakingAllTheTime();
}
new code:
void myMethod()
{
Thread t = new Thread(new Runnable()
{
public void run()
{
methodTakingAllTheTime(); // modify the internals of this method to check for interruption
}
});
t.join(5000); // 5 seconds
t.interrupt();
}
but again, for this to work well, you'll still have to modify methodTakingAllTheTime or that thread will just continue to run after you've called interrupt.
The correct answer is, I believe, to create a Runnable to execute the sub-program, and run this in a separate Thread. THe Runnable may be a FutureTask, which you can run with a timeout ("get" method). If it times out, you'll get a TimeoutException, in which I suggest you
call thread.interrupt() to attempt to end it in a semi-cooperative manner (many library calls seem to be sensitive to this, so it will probably work)
wait a little (Thread.sleep(300))
and then, if the thread is still active (thread.isActive()), call thread.stop(). This is a deprecated method, but apparently the only game in town short of running a separate process with all that this entails.
In my application, where I run untrusted, uncooperative code written by my beginner students, I do the above, ensuring that the killed thread never has (write) access to any objects that survive its death. This includes the object that houses the called method, which is discarded if a timeout occurs. (I tell my students to avoid timeouts, because their agent will be disqualified.) I am unsure about memory leaks...
I distinguish between long runtimes (method terminates) and hard timeouts - the hard timeouts are longer and meant to catch the case when code does not terminate at all, as opposed to being slow.
From my research, Java does not seem to have a non-deprecated provision for running non-cooperative code, which, in a way, is a gaping hole in the security model. Either I can run foreign code and control the permissions it has (SecurityManager), or I cannot run foreign code, because it might end up taking up a whole CPU with no non-deprecated means to stop it.
double x = 2.0;
while(true) {x = x*x}; // do not terminate
System.out.print(x); // prevent optimization
I can think of a not so great way to do this. If you can detect when it is taking too much time, you can have the method check for a boolean in every step. Have the program change the value of the boolean tooMuchTime to true if it is taking too much time (I can't help with this). Then use something like this:
Method(){
//task1
if (tooMuchTime == true) return;
//task2
if (tooMuchTime == true) return;
//task3
if (tooMuchTime == true) return;
//task4
if (tooMuchTime == true) return;
//task5
if (tooMuchTime == true) return;
//final task
}
I am currently interested in learning about Multi-threading. I have written a piece of code. And my question is if this the correct way. I later want to implement this in another code of mine. My idea was to run multiple threads existing of the same class. So let's say 5 threads and they all have a runner class inside them. What I want to implement in another code, is that I want to run multiple browsers at once. So, I have a class Browser. And then I have 5 threads with the class Browser. And they are all working simultaneously but don't know each other, so they don't have any interaction with each other at all.
So is this idea OK then?
class Runner implements Runnable {
public void run() {
for(int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " - " + i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class BasisDemo {
public static void main(String[] args) {
Thread runner1 = new Thread(new Runner(), "Runner 1");
runner1.start();
Thread runner2 = new Thread(new Runner(), "Runner 2");
runner2.start();
}
}
Is this a good practise and does it support my idea?
Or is using multi-threading even unnecessary.
I don't know it for sure.
Thanks for helping me out.
So your idea would work. If you try this code below.
System.out.println(System.currentTimeMillis());
System.out.println(System.currentTimeMillis());
You will find that the time is actually the same, which mean these two lines are executed almost at the same time.
In term of your code:
Thread runner1 = new Thread(new Runner(), "Runner 1");
runner1.start();
Thread runner2 = new Thread(new Runner(), "Runner 2");
runner2.start();
These threads will be executed at almost the same time, that's why your idea will work.
To make it more accurate. You can switch your codes:
Thread runner1 = new Thread(new Runner(), "Runner 1");
Thread runner2 = new Thread(new Runner(), "Runner 2");
runner1.start();
runner2.start();
If you want to make the timing even more accurate. You can use CyclicBarrier. It allows a set of thread to wait for each other and start at the same time. Here is demo codes:
class Demo {
final CyclicBarrier barrier;
class Broswer implements Runnable {
Worker() { }
public void run() {
while (!done()) {
try {
// wait for other threads
barrier.await();
// work for something, in your case an hour, but how can you control that
// work....
// sleep for a certain time
sleep(certain time)
} catch (InterruptedException ex) {
return;
} catch (BrokenBarrierException ex) {
return;
}
}
}
}
public static main(String args[]) {
barrier = new CyclicBarrier(N);
for (int i = 0; i < N; ++i)
new Thread(new Broswer()).start();
// wait until all done, in your case, forever.
}
}
Sounds like you're on the right track. Each thread will have no reference of each other, since you defined them as separate objects. They would both be able to contain their own data, execute their own methods, completely independently of one another.
One way you could confirm they are executing simultaneously is to make your loop start from a random number, that way you will see the console output incrementing beginning from two different numbers. (i.e. 100, 50, 101, 102, 51, 52, ...)
What you have outlined is the most common way to create threads in Java, you can read more about it here if you have questions later on.
1 Thread, not 5
Or is using multi-threading even unnecessary. I don't know it for sure.
If using the same class to do the same work, then No, no need for 5 threads. You only need one thread to run a task daily in the background.
If you want a copy everyday of a daily newspaper, would you send one of you children to the store with a dollar in hand each morning or would you send five of your children each with a dollar in hand?
ScheduledExecutorService
Also, Java provide a slick facility for this kind of work where you are scheduling tasks to be done in the background regularly: ScheduledExecutorService. Search Stack Overflow for more info, and read the Oracle Tutorial on Executors.
I am quite new to Threads in Java, I am using an API which is using thread internally and listening data from the counter party, I am putting this data in an queue for further processing. I have created another Thread which is continuously reading this queue for retrieving data and processing and to write the results into text file. I am using while(true) statement to run infinite loop in thread this cause a hundred per cent of CPU usage and if I use sleep(10) in it add up latency which keep on increasing with time as I am receiving about 20 data item in one second.
public void run() {
while(true) {
try { Thread.sleep(10); }
catch (InterruptedException e2) { // TODO Auto-generated catch block
e2.printStackTrace();
}
if (!(queue.isEmpt())) {
Tick quote=queue.take();
processTuple(quote);
}
} // end while(true)
} // end run()
Could anyone suggest me solution where I can reduce CPU usage without adding latency.
Check out ArrayBlockingQueue.
EDIT:
Example of how to use a queue based on your code:
LinkedBlockingQueue<Tick> queue;
public void run() {
while (true) {
// No need to check the queue. No need to sleep().
// take() will wait until there's anything available
Tick quote = queue.take();
processTuple(quote);
}
}
Ya. Use a BlockingQueue implementation instead of busy- wait. while(true) will keep scheduling the thread.
Use queue implementations instead of Threads. See this link to know more about queue implementations. You can use ArrayBlockingQueue.
You may change your code something like this:
BlockingQueue<Tick> queue = ..
public void run()
{
for (Tick quote; quote = queue.take(); )
{
if (quote == someSpecialObjectToIndicateStop)
break; // To stop this thread Or you may catch InterruptedException
processTuple(quote);
}
}
See BlockingQueue documentation here
I have a while loop that needs to repeat once a second, and I have no idea how to do that. I have never even used Java's time module or whatever it is called.
The basic loop is shown below. Can anyone give me a tip on how to do this?
while (!isOver()) {
// do some work
}
Maybe this code snippet can help you out. It´s a scheduled timertask that will repeat the run() method every 1 second. Your can add whatever you want there.
TimerTask timerTask = new TimerTask()
{
public void run()
{
.... //Whatever inside your loop will be executed every second
}
};
....
Timer timer = new Timer();
timer.scheduleAtFixedRate(timerTask, 0, 1000);
I would probably use a thread, though depending on how fast your computer is, and how much work it needs to do for each iteration of the loop, it might not be perfect.
Each program has one thread at all times. If it doesn't, it's not a process. This is your main thread, it comes to "life" when your program starts, and dies when your program terminates. There is a static method on Thread called sleep(int ms). This suspends the processing of the thread until it's parameter (ms) milliseconds have elapsed. So Thread.sleep(1000) would suspend the thread for one second, then resume.
Suspending the main thread for one second each time looks like this:
while(!isOver()) {
// Do stuff
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// Deal with exception here
}
}
Hope this helps. There is another way to create threads, but for this purpose it's way too long and drawn out..
PS You need the try/catch because sometimes the System can interrupt your thread, and that will cause an exception. A simple e.printStackTrace() should let you know when it happens, but you might want to deal with it more explicitly for any production application.
while (!isOver()) {
// do some work
try {
Thread.sleep(1000); /* 1000ms or 1 second */
} catch(InterruptedException e) {
// handle
}
}
private void time() {
while (! isOver) {
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
//Do nothing, just loop
}
}
}
And then start that on another thread so your main thread will continue:
new Thread(this::time).start();
As you can see there are tons of ways to accomplish what you are looking to do. Here is another way. I tend to shy away from Timers if your code can throw exceptions as it will stop the Timer from running again. Something like this will work with a few less gotchas.
ScheduledExecutorService e = Executors.newSingleThreadScheduledExecutor();
e.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
}
}, 0, 1, TimeUnit.SECONDS);
}
Or if you wanted to do a sleep you could try:
while(!isOver) {
//DO WORK
try {
//Be careful if you are holding any Locks they will not be released
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
//Do nothing, just loop
}
}