Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I would like to create a code-competition in Java. The basic plan is:
Each competitor submits a class that implements the Function interface.
I apply the function of each submitted class on a set of pre-made inputs.
The grade of each submission is its number of correct outputs.
Now, I want to add a timeout: each class is allowed to run for at most 1 second on each input. If a class runs for more than one second, it should be stopped and graded 0 on that input.
My initial idea was to run each test in a separate thread, and stop the thread after a second. However, to stop a thread in Java, it is required to change its code. Here, the code is submitted by other people and I do not want to read all the submissions to verify that they allow interruption.
How can I implement such a competition?
Threads are not guaranteed to share resources fairly. Therefore, wall clock time in a "online judge" should be suspect, especially with the upper limit set in the second or minute range.
If you want to determine if people are using optimized solutions, perhaps you could set the limit a lot higher and add a few test cases with data sets that assured one was using a reasonable algorithm. With a ten minutes to compete, the odds of small scheduling differences is average out in ways that obliterate the need for more sophisticated CPU time measurements.
As for the Thread safety, you'd probably want to not use Threads in this case. Spawning a process would offload the online judge, prevent one contestant from possibly inspecting / interfering with another, provide an obvious means of termination (by the kill signal), and permit better bench marking of time (akin to the Unix command "time").
When something goes wrong in a threaded environment, it has the potential to destabilize the program, by using processes, extra barriers will prevent any such destabilization from impacting your online judge.
Using Junit? You could give this a try:
https://github.com/junit-team/junit4/wiki/timeout-for-tests
So One way that you could implement this would be to use two separate threads for 1 competitor. A ThreadTimer and A ThreadHelper
public class ThreadTimer extends Thread {
public ThreadTimer() {
}
#Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(ThreadTimer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
And ThreadHelper Which runs the function
public class ThreadHelper extends Thread {
Calculator c;
public ThreadHelper(Calculator c) {
this.c = c;
}
public Calculator getC() {
return c;
}
public void setC(Calculator c) {
this.c = c;
}
#Override
public void run() {
long startTime = System.nanoTime();
long plus = c.add();
long endTime = System.nanoTime();
long duration = (endTime - startTime);
long seconds = duration / 1000000000;
System.out.println("Add Time: " + seconds);
}
}
Your interface you created I am calling Calculator in my code.
This is calculating how long add takes and outputs the duration. I am sure the calculations are much more complex, but a potential answer to your question would come in the startup class:
public class Competition {
public static void main(String[] args) throws InterruptedException, Exception {
Calculator jim = new JimSmithsCalculator();
Calculator john = new JohnDoesCalculator();
ThreadHelper jimsThread = new ThreadHelper(jim);
ThreadTimer time1 = new ThreadTimer();
ThreadHelper JohnsThread = new ThreadHelper(john);
ThreadTimer time2 = new ThreadTimer();
time1.start();
jimsThread.start();
//This will run a loop ensuring both of the above threads are terminated...
checkSeconds(time1, jimsThread);//This also does the time check
//...Before moving on to these threads.
time2.start();
JohnsThread.start();
checkSeconds(time2, JohnsThread);
}
public static void checkSeconds(ThreadTimer time, ThreadHelper t) throws Exception {
while (t.isAlive()) {
if (time.getState() == Thread.State.TERMINATED) {
throw new Exception(t.getName() + " >> " + t.getClass() + " Failed!!!");
}
}
}
}
Since You can not use the stop() method anymore, you could throw an exception if ThreadTimer completes before ThreadHelper does.
This will output an exception and continue the program. You could then see that a competitors thread failed with the exception.
The main point to all of this random code and my answer to your question is this method :
public static void checkSeconds(ThreadTimer time, ThreadHelper t) throws Exception {
while (t.isAlive()) {
if (time.getState() == Thread.State.TERMINATED) {
throw new Exception(t.getName() + " >> " + t.getClass() + " Failed!!!");
}
}
}
I don't know if this would work exactly as you would want it.
I hope this at least sparks an idea.
Related
I'm working at the moment on a simple Chess A.I. (calculate possible future turns, rate them, chosse the best one, + some tricks so you don't have to calculate every single turn). The code is written in Java and I'm using Netbeans. To make the calculations faster, I use multithreading. The code works roughly like this:
Main function makes first some calculations and then starts 8 threads.
the threads execute the main-calculations
when they finish, they set a boolean value in a boolean array (finished[]) true. This array is in the "main Class" (if you call it like this), where also the main function is.
during all this time the main function is waiting and checking constantly if every value of the finished[] - array is true. If that is the case, it continues it's work.
Now I have a strange problem. The code works perfectly on my PC, but when I run the EXACT same code on my laptop, the main function won't continue its work, after all values of the finished[]-array are true. I already made some changes in the code, so I can try it with different numbers of threads, but the result is always the same.
I have totally no idea what's going on here and would really appreciate it, if someone of you had any answers and/or suggestions!
If you need any more Information just ask, I'll try my best. :)
(Sorry for possible grammar mistakes, english isn't my native language, but I'm trying my best. ;))
So I was asked to show some Code I used in the program:
(Perhaps first a warning, yes I am still a big Noob in Java and this is my first time I work with threads so don't be shocked if you see terrible mistakes I possibly made. xD)
The main Class looks something like this:
public class Chess_ai_20 {
static boolean finished[] = new boolean[8];
Distributor[] Distributors = new Distributor[8];
...
public static void main(String[] args) {
boolean testing=false;
...
//some calculations and other stuff
...
Distributors[0] = new Distributor(...., "0"); //the String "0" will be the thread name.
Distributors[1] = new ...
...
Distributors[7] = new Distributor(...., "7");
for (int i = 0; i < 8; i++) {
Distributoren[i].start();
}
testing=false;
while(testing==false){
if(finished[0]==true && finished[1]==true && ... && finished[7]==true){
testing=true; //That's the point where I get stuck I suppose
}
}
System.out.println("I made it!");
}
public static void setFinished(int i) {
finished[i] = true;
System.out.println("finished [" + i + "] = " + finished[i]);
System.out.println(Arrays.toString(finished)); //To check how many values already are true
}
}
Then we got of course the class "Distributor"
public class Distributor extends Thread {
Thread t;
String threadname;
boolean running=false;
...
Distributor(......, String s) {
threadname=s;
...
...
}
#Override
public void start() {
running=true;
if (t == null) {
t = new Thread(this,threadname);
t.start();
}
}
#Override
public void run() {
if(running){
...
//Do the main calculations etc.
...
//All the Calculations habe been done at this point
Chess_ai_20.setFinished(Character.getNumericValue(threadname.charAt(0))); //Set the value of finished[] true in the main class
running=false;
}
}
}
As others have mentioned, using a Future would be much simpler and easy to understand. Below is a snippet demonstrating how you could rewrite your code. Check out the code in action.
First, you write a Callable to define the task that you want to do.
public class MyCallable implements Callable<Boolean> {
#Override
public Boolean call() {
// Do some job and return the result.
return Boolean.TRUE;
}
}
And then, you submit this task to an Executor. There are a lot of Executors in JDK. You want to go through the Concurrency Tutorial first.
ExecutorService executor = Executors.newFixedThreadPool(Runtime
.getRuntime().availableProcessors());
List<Callable<Boolean>> callables = new ArrayList<>();
for (int counter = 0; counter < 8; counter++) {
callables.add(new MyCallable());
}
List<Future<Boolean>> futures = executor.invokeAll(callables);
for (Future<Boolean> future : futures) {
System.out.println(future.get()); // You'd want to store this into an array or wherever you see fit.
}
executor.shutdown();
Remember that the futures returned by the executor are in the same order as the Callables you submitted (or added) to the Collection (in this case, an ArrayList). So you don't need to worry about returning the index, an ID or even the name of the Thread (if you assigned one) to map the corresponding result.
This question already has answers here:
How should I unit test multithreaded code?
(29 answers)
Closed 5 years ago.
How do I test something like this in multithreaded environment. I know it's gonna fail, cause this code is not thread-safe. I just wanna know how can i prove it? Creating bunch of threads and trying to add with those different threads? This code is intentionally not written properly cause of testing purposes !!!
public class Response_Unit_Manager {
private static HashMap<String, Response_Unit> Response_Unit_DB =
new HashMap<> ();
/**
*
* This subprogram adds a new Response_Unit to the data store. The
* new response unit must be valid Response_Unit object and it's ID must be
* unique (i.e., must not already exist in the data store.
*
* Exceptions Thrown: Null_Object_Exception
*/
public static void Add_Response_Unit (Response_Unit New_Unit)
throws Null_Object_Exception, Duplicate_Item_Exception {
String Unit_ID = New_Unit.Unit_ID ();
if (New_Unit == null)
throw new Null_Object_Exception ();
else if (Response_Unit_Exists (Unit_ID))
throw new Duplicate_Item_Exception (Unit_ID);
else
Response_Unit_DB.put (Unit_ID, New_Unit);
} //end Add_Response_Unit
You may get lucky and see a failure when running a test, but non-failing code doesn't mean that it's thread-safe code. The only automated ways to check thread-safety is with some static analysis tools that let you put annotations on methods/classes and scan for potential issues. For example, I know FindBugs support some annotations and does concurrency checking based on them. You should be able to apply this to your single Tester class. There is still a lot of room for improvement in the industry on this topic, but here are some current examples:
http://robertfeldt.net/publications/grahn_2010_comparing_static_analysis_tools_for_concurrency_bugs.pdf
http://homepages.inf.ed.ac.uk/dts/students/spathoulas/spathoulas.pdf
As others have noted, you can't write a test that will guarantee failure as the thread schedule might "just work out", but you can write tests that have a very low probability of passing if there are thread safety issues. For example, you're code attempts to disallow duplicate items in your DB but due to thread safety issues it can't do that. So spawn a ton of threads, have them all wait on a CountdownLatch or something to maximize your chances of triggering the race, then have them all try to insert the same item. Finally you can check that (a) all but one thread saw a Duplicate_Item_Exception and (b) Response_Unit_DB contains only a single item. For these kinds of tests you can also run it several times (in the same test) to maximize your chances of triggering the issue.
Here's an example:
#Test
public void testIsThreadSafe() {
final int NUM_ITERATIONS = 100;
for(int i = 0; i < NUM_ITERATIONS; ++i) {
oneIsThreaSafeTest();
}
}
public void oneIsThreadSafeTest() {
final int NUM_THREADS = 1000;
final int UNIT_ID = 1;
final Response_Unit_Manager manager = new Response_Unit_Manager();
ExecutorService exec = Executors.newFixedThreadPool(NUM_THREADS);
CountdownLatch allThreadsWaitOnThis = new CountdownLatch(1);
AtomicInteger numThreadsSawException = new AtomicInteger(0);
for (int i = 0; i < NUM_THREADS; ++i) {
// this is a Java 8 Lambda, if using Java 7 or less you'd use a
// class that implements Runnable
exec.submit(() -> {
allThreadsWaitOnThis.await();
// making some assumptions here about how you construct
// a Response_Unit
Response_Unit unit = new Response_Unit(UNIT_ID);
try {
manager.Add_Response_Unit(unit);
} catch (Duplicate_Item_Exception e) {
numThreadsSawException.incrementAndGet();
}
});
// release all the threads
allThreadsWaitOnThis.countdown();
// wait for them all to finish
exec.shutdown();
exec.awaitTermination(10, TimeUnits.MINUTES);
assertThat(numThreadsSawException.get()).isEqualTo(NUM_THREADS - 1);
}
You can construct similar tests for the other potential thread safety issues.
The easiest way to find errors with testing, like the one which is contained in your class, is to use a Testrunner like for example the following:
package com.anarsoft.mit;
import java.util.concurrent.atomic.AtomicInteger;
public class Test_Response_Unit_Manager implements Runnable {
private final AtomicInteger threadCount = new AtomicInteger();
public void test() throws Exception
{
for(int i = 0; i < 2 ;i++)
{
Thread thread = new Thread(this, "Thread " + i);
this.threadCount.incrementAndGet();
thread.start();
}
while( this.threadCount.get() > 0 )
{
Thread.sleep(1000);
}
Thread.sleep(10 * 1000);
}
public void run()
{
exec();
threadCount.decrementAndGet();
}
protected void exec()
{
Response_Unit_Manager.Add_Response_Unit(new Response_Unit(Thread.currentThread().getId()));
}
public static void main(String[] args) throws Exception
{
(new Test_Response_Unit_Manager()).test();
}
}
And to use a dynamic race condition detection tool like http://vmlens.com, a lightweight race condition detector. This will show you the following race conditions:
And the stacktraces leading to the bug. On the left the write and one the right the read.
http://vmlens.com works with eclipse, so it depens on the ide you are using, if its useful for you
There is a question which was recently asked to me in an interview.
Problem: There is a class meant to profile the execution time of the code. The class is like:
Class StopWatch {
long startTime;
long stopTime;
void start() {// set startTime}
void stop() { // set stopTime}
long getTime() {// return difference}
}
The client is expected to create an instance of the StopWatch and call methods accordingly. User code can mess up the use of the methods leading to unexpected results. Ex, start(), stop() and getTime() calls should be in order.
This class has to be "reconfigured" so that user can be prevented from messing up the sequence.
I proposed use of custom exception if stop() is called before start(), or doing some if/else checks, but interviewer was not satisfied.
Is there a design pattern to handle these kind of situations?
Edit: The class members and method implementations can be modified.
First there is the fact that implementing an own Java profiler is a waste of time, since good ones are available (maybe that was the intention behind the question).
If you want to enforce the correct method order at compile time, you have to return something with each method in the chain:
start() has to return a WatchStopper with the stop method.
Then WatchStopper.stop() has to return a WatchResult with the getResult() method.
External Construction of those helper classes as well as other ways of accessing their methods have to be prevented of course.
With minor changes to the interface, you can make the method sequence the only one that can be called - even at compile time!
public class Stopwatch {
public static RunningStopwatch createRunning() {
return new RunningStopwatch();
}
}
public class RunningStopwatch {
private final long startTime;
RunningStopwatch() {
startTime = System.nanoTime();
}
public FinishedStopwatch stop() {
return new FinishedStopwatch(startTime);
}
}
public class FinishedStopwatch {
private final long elapsedTime;
FinishedStopwatch(long startTime) {
elapsedTime = System.nanoTime() - startTime;
}
public long getElapsedNanos() {
return elapsedTime;
}
}
The usage is straightforward - every method returns a different class which only has the currently applicable methods. Basically, the state of the stopwatch is encapsuled in the type system.
In comments, it was pointed out that even with the above design, you can call stop() twice. While I consider that to be added value, it is theoretically possible to screw oneself over. Then, the only way I can think of would be something like this:
class Stopwatch {
public static Stopwatch createRunning() {
return new Stopwatch();
}
private final long startTime;
private Stopwatch() {
startTime = System.nanoTime();
}
public long getElapsedNanos() {
return System.nanoTime() - startTime;
}
}
That differs from the assignment by omitting the stop() method, but that's potentially good design, too. All would then depend on the precise requirements...
We commonly use StopWatch from Apache Commons StopWatch check the pattern how they've provided.
IllegalStateException is thrown when the stop watch state is wrong.
stop
public void stop()
Stop the stopwatch.
This method ends a new timing session, allowing the time to be retrieved.
Throws:
IllegalStateException - if the StopWatch is not running.
Straight forward.
Maybe he expected this 'reconfiguration' and question was not about method sequence at all:
class StopWatch {
public static long runWithProfiling(Runnable action) {
startTime = now;
action.run();
return now - startTime;
}
}
Once given more thought
In hindsight it sounds like they were looking for the execute around pattern. They're usually used to do things like enforce closing of streams. This is also more relevant due to this line:
Is there a design pattern to handle these kind of situations?
The idea is you give the thing that does the "executing around" some class to do somethings with. You'll probably use Runnable but it's not necessary. (Runnable makes the most sense and you'll see why soon.) In your StopWatch class add some method like this
public long measureAction(Runnable r) {
start();
r.run();
stop();
return getTime();
}
You would then call it like this
StopWatch stopWatch = new StopWatch();
Runnable r = new Runnable() {
#Override
public void run() {
// Put some tasks here you want to measure.
}
};
long time = stopWatch.measureAction(r);
This makes it fool proof. You don't have to worry about handling stop before start or people forgetting to call one and not the other, etc. The reason Runnable is nice is because
Standard java class, not your own or third party
End users can put whatever they need in the Runnable to be done.
(If you were using it to enforce stream closing then you could put the actions that need to be done with a database connection inside so the end user doesn't need to worry about how to open and close it and you simultaneously force them to close it properly.)
If you wanted, you could make some StopWatchWrapper instead leave StopWatch unmodified. You could also make measureAction(Runnable) not return a time and make getTime() public instead.
The Java 8 way to calling it is even simpler
StopWatch stopWatch = new StopWatch();
long time = stopWatch.measureAction(() - > {/* Measure stuff here */});
A third (hopefully final) thought: it seems what the interviewer was looking for and what is being upvoted the most is throwing exceptions based on state (e.g., if stop() is called before start() or start() after stop()). This is a fine practice and in fact, depending on the methods in StopWatch having a visibility other than private/protected, it's probably better to have than not have. My one issue with this is that throwing exceptions alone will not enforce a method call sequence.
For example, consider this:
class StopWatch {
boolean started = false;
boolean stopped = false;
// ...
public void start() {
if (started) {
throw new IllegalStateException("Already started!");
}
started = true;
// ...
}
public void stop() {
if (!started) {
throw new IllegalStateException("Not yet started!");
}
if (stopped) {
throw new IllegalStateException("Already stopped!");
}
stopped = true;
// ...
}
public long getTime() {
if (!started) {
throw new IllegalStateException("Not yet started!");
}
if (!stopped) {
throw new IllegalStateException("Not yet stopped!");
}
stopped = true;
// ...
}
}
Just because it's throwing IllegalStateException doesn't mean that the proper sequence is enforced, it just means improper sequences are denied (and I think we can all agree exceptions are annoying, luckily this is not a checked exception).
The only way I know to truly enforce that the methods are called correctly is to do it yourself with the execute around pattern or the other suggestions that do things like return RunningStopWatch and StoppedStopWatch that I presume have only one method, but this seems overly complex (and OP mentioned that the interface couldn't be changed, admittedly the non-wrapper suggestion I made does this though). So to the best of my knowledge there's no way to enforce the proper order without modifying the interface or adding more classes.
I guess it really depends on what people define "enforce a method call sequence" to mean. If only the exceptions are thrown then the below compiles
StopWatch stopWatch = new StopWatch();
stopWatch.getTime();
stopWatch.stop();
stopWatch.start();
True it won't run, but it just seems so much simpler to hand in a Runnable and make those methods private, let the other one relax and handle the pesky details yourself. Then there's no guess work. With this class it's obvious the order, but if there were more methods or the names weren't so obvious it can begin to be a headache.
Original answer
More hindsight edit: OP mentions in a comment,
"The three methods should remain intact and are only interface to the programmer. The class members and method implementation can change."
So the below is wrong because it removes something from the interface. (Technically, you could implement it as an empty method but that seems to be like a dumb thing to do and too confusing.) I kind of like this answer if the restriction wasn't there and it does seem to be another "fool proof" way to do it so I will leave it.
To me something like this seems to be good.
class StopWatch {
private final long startTime;
public StopWatch() {
startTime = ...
}
public long stop() {
currentTime = ...
return currentTime - startTime;
}
}
The reason I believe this to be good is the recording is during object creation so it can't be forgotten or done out of order (can't call stop() method if it doesn't exist).
One flaw is probably the naming of stop(). At first I thought maybe lap() but that usually implies a restarting or some sort (or at least recording since last lap/start). Perhaps read() would be better? This mimics the action of looking at the time on a stop watch. I chose stop() to keep it similar to the original class.
The only thing I'm not 100% sure about is how to get the time. To be honest that seems to be a more minor detail. As long as both ... in the above code obtain current time the same way it should be fine.
I suggest something like:
interface WatchFactory {
Watch startTimer();
}
interface Watch {
long stopTimer();
}
It will be used like this
Watch watch = watchFactory.startTimer();
// Do something you want to measure
long timeSpentInMillis = watch.stopTimer();
You can't invoke anything in wrong order. And if you invoke stopTimer twice you get meaningful result both time (maybe it is better rename it to measure and return actual time each time it invoked)
Throwing an exception when the methods are not called in the correct order is common. For example, Thread's start will throw an IllegalThreadStateException if called twice.
You should have probably explained better how the instance would know if the methods are called in the correct order. This can be done by introducing a state variable, and checking the state at the start of each method (and updating it when necessary).
This can also be done with Lambdas in Java 8. In this case you pass your function to the StopWatch class and then tell the StopWatch to execute that code.
Class StopWatch {
long startTime;
long stopTime;
private void start() {// set startTime}
private void stop() { // set stopTime}
void execute(Runnable r){
start();
r.run();
stop();
}
long getTime() {// return difference}
}
Presumably the reason for using a stopwatch is that the entity that's interested in the time is distinct from the entity that's responsible for starting and stopping the timing intervals. If that is not the case, patterns using immutable objects and allowing code to query a stop watch at any time to see how much time has elapsed to date would likely be better than those using a mutable stopwatch object.
If your purpose is to capture data about how much time is being spent doing various things, I would suggest that you might be best served by a class which builds a list of timing-related events. Such a class may provide a method to generate and add a new timing-related event, which would record a snapshot of its created time and provide a method to indicate its completion. The outer class would also provide a method to retrieve a list of all timing events registered to date.
If the code which creates a new timing event supplies a parameter indicating its purpose, code at the end which examines the list could ascertain whether all events that were initiated have been properly completed, and identify any that had not; it could also identify if any events were contained entirely within others or overlapped others but were not contained within them. Because each event would have its own independent status, failure to close one event need not interfere with any subsequent events or cause any loss or corruption of timing data related to them (as might occur if e.g. a stopwatch had been accidentally left running when it should have been stopped).
While it's certainly possible to have a mutable stopwatch class which uses start and stop methods, if the intention is that each "stop" action be associated with a particular "start" action, having the "start" action return an object which must be "stopped" will not only ensure such association, but it will allow sensible behavior to be achieved even if an action is started and abandoned.
I know this already has been answered but couldn't find an answer invoking builder with interfaces for the control flow so here is my solution :
(Name the interfaces in a better way than me :p)
public interface StartingStopWatch {
StoppingStopWatch start();
}
public interface StoppingStopWatch {
ResultStopWatch stop();
}
public interface ResultStopWatch {
long getTime();
}
public class StopWatch implements StartingStopWatch, StoppingStopWatch, ResultStopWatch {
long startTime;
long stopTime;
private StopWatch() {
//No instanciation this way
}
public static StoppingStopWatch createAndStart() {
return new StopWatch().start();
}
public static StartingStopWatch create() {
return new StopWatch();
}
#Override
public StoppingStopWatch start() {
startTime = System.currentTimeMillis();
return this;
}
#Override
public ResultStopWatch stop() {
stopTime = System.currentTimeMillis();
return this;
}
#Override
public long getTime() {
return stopTime - startTime;
}
}
Usage :
StoppingStopWatch sw = StopWatch.createAndStart();
//Do stuff
long time = sw.stop().getTime();
As Per Interview question ,It seems to like this
Class StopWatch {
long startTime;
long stopTime;
public StopWatch() {
start();
}
void start() {// set startTime}
void stop() { // set stopTime}
long getTime() {
stop();
// return difference
}
}
So now All user need to create object of StopWatch class at beginning and getTime() need to call at End
For e.g
StopWatch stopWatch=new StopWatch();
//do Some stuff
stopWatch.getTime()
I'm going to suggest that enforcing the method call sequence is solving the wrong problem; the real problem is a unfriendly interface where the user must be aware of the state of the stopwatch. The solution is to remove any requirement to know the state of the StopWatch.
public class StopWatch {
private Logger log = Logger.getLogger(StopWatch.class);
private boolean firstMark = true;
private long lastMarkTime;
private long thisMarkTime;
private String lastMarkMsg;
private String thisMarkMsg;
public TimingResult mark(String msg) {
lastMarkTime = thisMarkTime;
thisMarkTime = System.currentTimeMillis();
lastMarkMsg = thisMarkMsg;
thisMarkMsg = msg;
String timingMsg;
long elapsed;
if (firstMark) {
elapsed = 0;
timingMsg = "First mark: [" + thisMarkMsg + "] at time " + thisMarkTime;
} else {
elapsed = thisMarkTime - lastMarkTime;
timingMsg = "Mark: [" + thisMarkMsg + "] " + elapsed + "ms since mark [" + lastMarkMsg + "]";
}
TimingResult result = new TimingResult(timingMsg, elapsed);
log.debug(result.msg);
firstMark = false;
return result;
}
}
This allows a simple use of the mark method with a result returned and logging included.
StopWatch stopWatch = new StopWatch();
TimingResult r;
r = stopWatch.mark("before loop 1");
System.out.println(r);
for (int i=0; i<100; i++) {
slowThing();
}
r = stopWatch.mark("after loop 1");
System.out.println(r);
for (int i=0; i<100; i++) {
reallySlowThing();
}
r = stopWatch.mark("after loop 2");
System.out.println(r);
This gives the nice result of;
First mark: [before loop 1] at time 1436537674704
Mark: [after loop 1] 1037ms since mark [before loop 1]
Mark: [after loop 2] 2008ms since mark [after loop 1]
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I know some basic concepts in java multithreading.But now i want to create 5 threads that should work concurrently.How can i get execution time of a thread?...Somebody please help me with the deep concepts of threads including methods and purposes.
Your question is really unclear. What do you mean by execution time of a thread? When it started vs. when it stopped (wall time) Or how long it was actually running, not including times it was on hold (i.e., CPU time)?
Take a look at Monitor cpu usage per thread in java?
BTW, Threading isn't something you can simply learn from a StackOverflow answer.
The official guide to Java explains concurrency quite well:
http://docs.oracle.com/javase/tutorial/essential/concurrency/
The book "Java Concurrency in Practice" is even better.
Make a proxy
class Proxy implements Runnable {
final Runnable target;
Proxy(Runnable target) {
this.target = target;
}
public void run() {
long t0 = System.currentTimeMillis();
try {
target.run();
} finally {
System.out.println(Thread.currentThread() + " execution time = " + (System.currentTimeMillis() - t0));
}
}
}
and use it
new Thread(new Proxy(task)).start();
You can use the methods of
ThreadMxBean interface
you can get the instance using
ManagementFactory.getThreadMXBean();
after that you can call a method
getThreadCpuTime(Thread.currentThread().getId());
so your code will look like
ManagementFactory.getThreadMXBean.getThreadCpuTime(Thread.currentThread().getId());
for more details see Docs
Something like this code could be useful http://blog.sheidaei.com/2013/06/simple-thread-example-in-java.html.
You can use System.currentTimeMillis() instead of System.out.println() to get the execution time of the threads.
/**
* Created with IntelliJ IDEA.
* User: shahin
* Date: 6/5/13
* Time: 11:32 PM
* To change this template use File | Settings | File Templates.
*/
public class SimpleThread implements Runnable{
public SimpleThread(String simpleName) {
this.simpleName = simpleName;
System.out.println(">>> Constructor for " + getSimpleName());
}
public String getSimpleName() {
return simpleName;
}
public void setSimpleName(String simpleName) {
this.simpleName = simpleName;
}
private String simpleName;
#Override
public void run() {
System.out.println(" >> "+getSimpleName() + " started.");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
System.out.println(" >> "+getSimpleName() + " stopped.");
}
public static void main(String args[])
{
System.out.println("Main Thread started.");
SimpleWaitNotifyThread simpleThread;
Thread thread;
for(int i=0;i<5;i++)
{
simpleThread = new SimpleWaitNotifyThread("Thread "+(i+1));
thread = new Thread(simpleThread,"Thread "+(i+1));
thread.start();
}
System.out.println("Main Thread finished.");
}
}
I'm trying to make a function which can ONLY be called again after there is some amount of time delay between the two calls, (Say 5 seconds).
I require this functionality for an android app I'm creating.
Since it is possible that the user would be calling that function too frequently within a few seconds, it would destroy his experience. Hence, I'm desperately looking for an answer on this.
public void doSomethin(){
//code here which makes sure that this function has not been called twice within the specified delay of 5 seconds
//Some code here
}
Any help would be awesome!
Adit
You could hold the time in milliseconds and check if the current time is greater than or equal to the previous time + 5 seconds. If it is, execute the method and replace the previous time with the current time.
See System.currentTimeMillis()
public class FiveSeconds {
private static Scanner scanner = new Scanner(System.in);
private static long lastTime = 0;
public static void main(String[] args) {
String input = scanner.nextLine();
while(!input.equalsIgnoreCase("quit")){
if(isValidAction()){
System.out.println(input);
lastTime = System.currentTimeMillis();
} else {
System.out.println("You are not allowed to do this yet");
}
input = scanner.nextLine();
}
}
private static boolean isValidAction(){
return(System.currentTimeMillis() > (lastTime + 5000));
}
}
If the code runs on your main thread, Thread.sleep(5000) is not an option. The easiest way to go then would be:
private long previous = 0;
public void doSomething() {
long now = Calendar.getInstance().getTimeInMillis();
if (now - previous < 5000)
return;
previous = now;
// do something
}
use a static field, which saves the datetime of last execution and before executing check the current datetime against this timestamp.
I won't write code for you but if you think a bit about this it's not that hard. You want to make sure it's not called before 5 seconds has passed since last function call. Let's split this into parts.
1) Get current time
2) Compare to stored time that keeps it value between calls.
3) If less than 5 seconds has passed don't do anything
4) Otherwise store the new value and do stuff.
I never did coding in Android. But if Android has threads (which is most likely, it does). Then within this function sleep the thread for 5 seconds, it means even though it is called, it won't be executed further until 5 seconds are passed
public void doSomething()
{
Thread.sleep(5000); // Please find the corresponding Android method
}
make doSomethin() as a private method.
Expose another function say exposedDoSomething().
public void exposeDoSomething(){
// Add to a queue
}
In a separate thread read the queue in every 5 mins and call doSomethin()
Maybe a TimerTask will help you, more details here:
TimerTask|Android Developers
Example:
private TimerTask tiemrTast= new TimerTask() {
#Override
public void run() {
}
};
And then use this method: public void scheduleAtFixedRate (TimerTask task, long delay, long period)
One problem is that you'll have to have a session level timer for each and every user. This could be a fair amount of overhead depending on how many simultaneous users you have.
It's easy for one user: start a timer on request. It's distinguishing between users that's the problem. Your service is now stateful, which is usually a bad thing. You're giving away idempotence.
You could also maintain state in a database. Don't worry about calls; check persistent operations to make sure they don't happen too frequently.
It's not clear to me whether you mean to exclude all users for five seconds once the method is called by anyone, or if every user is prevented from calling the method again for five seconds once it's called the first time.
This sounds like a throughput killer. I'd reconsider this design.
you can use hander.postDalayed method to call method to run after specific delay
you can use your method something like this
int delay=5000;
int k;
int iDelayTimeInMiliSeconds=2000;
for( k=0;k<arrBatch.size();k++)
{
delay=delay+iDelayTimeInMiliSeconds;
callAllDocumentList(arrBatch.get(k),k,delay);
}
public void callAllDocumentList(final String strInvoiceId,final int count,int delay)
{
mHandler.postDelayed(new Runnable()
{
#Override
public void run()
{
// call your function here that you want to call after specific delay
//getOrderDetails(strInvoiceId,count,true);
}
}, delay);
}