Disable Thread.sleep() - java

I want to disable possibility of using Thread.sleep() in a java project and use my own method instead:
sleep(int time, String info)
That will wait for given amount of time, and print info why is waiting necessary here.
Is disabling Thread.sleep() possible?
If yes, what's best method to do so?

The best method would be to have hook on some static code analysis tool to mark build as failed if there are any invocations of Thread.Sleep().
You could probably configure SonarCube to do this.

You can use AOP to intercept calls to Thread.sleep() and "redirect" call to your one via aroundAdvice. When original Thread.sleep() is invoked, a "default cause" is added. This one shows an example about how you can use it (remember to create a AspectJ project, or Aspects will not work):
SleepAspect.java
package org.norsam.so.sleep
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
#Aspect
public class SleepAspect
{
#Around("call (* java.lang.Thread.sleep(..) )")
public Object aroundAdvice(ProceedingJoinPoint point) throws Throwable
{
StackTraceElement ste = Thread.currentThread().getStackTrace()[2];
Long ms = (Long) point.getArgs()[0];
String m = ste.getMethodName();
String c = ste.getClassName();
String skip = SleepClass.class.getName();
if (c.equals(skip) && m.equals("sleep")) {
System.out.println("sleep well for " + ms + "ms!");
} else {
SleepClass.sleep(ms, "Thread.sleep invoked in " + c + "." + m + ", no cause present!");
}
Object toret = point.proceed();
return toret;
}
}
SleepClass.java
package org.norsam.so.sleep
public class SleepClass {
public static void sleep(long l, String cause) {
System.out.println("CAUSE: " + cause);
try {
Thread.sleep(l);
} catch (InterruptedException e) {
}
}
public static void main(String[] args) throws InterruptedException {
SleepClass.sleep(1000, "I love to sleep 1000");
Thread.sleep(2000L);
System.out.println("Bye");
}
}
When you run it, you receive something like
CAUSE: I love to sleep 1000
sleep well for 1000ms!
CAUSE: Thread.sleep invoked in org.norsam.so.sleep.SleepClass.main, no cause present!
sleep well for 2000ms!
Bye

Yes, sure.
Just make sure that no code in that project is calling Thread.sleep(); but your MyUtility.sleep() replacement.
If the question is: can I somehow change the behavior of the existing Thread.sleep(), then the answer is: depends on context/effort you are willing to spend.
Well, with certain tricks; it might be possible; but simply speaking: it is a most likely a bad idea; and not worth following up on. I would really shy away from changing the code behavior, if at all I would look into those solutions that can identify usages of that unwanted sleep calls at compile time.

Related

How to terminate a task and continue the next one after a specified time limit? [duplicate]

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
}

Implementing a code-competition with timeout [closed]

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.

Java Design Issue: Enforce method call sequence

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]

Is this an efficient way to obfuscate code and is it performance friendly?

So I recently thought of a way that would make code de-obfuscation a lot more difficult. But I am not quite sure if this affects the performance of my code negatively: So my idea is to turn this code:
public class SpeedTest1 {
public static void main(String[] args){
long start = System.currentTimeMillis();
String toEncode = "fhsdakjfhasdkfhdsajkhfkshfv ksahyfvkawksefhkfhskfhkjsfhsdkfhjfhskjhafjkhskjadfhksdfhkjsdhfksfhksdhfsdyfieyt893489ygfudhgiueryriohetyuieyiuweatiuewytiueaytuiwfytwuiediuvnhuighsiudghfjdkghfsdkjghdiugfdkghdkjghdfkghfdghdigyeuriyeibuityeuirtuireytiuerythgfdkgiuegduigkghfdjkghjgkdfhgjfdhgjfdghfdkjghfdjkghfdkjghfdjkgfdjkghfdkjghfdjkgfdkjghfdkjgheriytretyretrityreiutyeriuhslfjlflkfflksdjflkjflks";
String str = Base64.encode(toEncode.getBytes());
try {
System.out.println(new String(Base64.decode(str), "UTF-8"));
} catch (Base64DecodingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println("Time: " + (end - start));
}
}
Into this code:
public class SpeedTest2 {
public static void main(String[] args){
long start = System.currentTimeMillis();
System.out.println(y(x(z(a().getBytes()))));
long end = System.currentTimeMillis();
System.out.println("Time: " + (end - start));
}
private static String y(byte[] b){
try {
return new String(b, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
private static byte[] x(String s){
try {
return Base64.decode(s);
} catch (Base64DecodingException e) {
e.printStackTrace();
}
return null;
}
private static String z(byte[] b){
return Base64.encode(b);
}
private static String a(){
return "fhsdakjfhasdkfhdsajkhfkshfv ksahyfvkawksefhkfhskfhkjsfhsdkfhjfhskjhafjkhskjadfhksdfhkjsdhfksfhksdhfsdyfieyt893489ygfudhgiueryriohetyuieyiuweatiuewytiueaytuiwfytwuiediuvnhuighsiudghfjdkghfsdkjghdiugfdkghdkjghdfkghfdghdigyeuriyeibuityeuirtuireytiuerythgfdkgiuegduigkghfdjkghjgkdfhgjfdhgjfdghfdkjghfdjkghfdkjghfdjkgfdjkghfdkjghfdjkgfdkjghfdkjgheriytretyretrityreiutyeriuhslfjlflkfflksdjflkjflks";
}
}
Now the second piece is more difficult to figure out about what it does. But now I am worried about the performance of my programm so I added the check time lines to see if one of the two is faster that the other one. Now most of the time they both print 0 as the time but sometimes one of the two print someting like 15 but that's never the same method. I did find this answer [java how expensive is a method call that states that Java itself optimizes the code at run time so that would mean that it doesn't matter wich of the two examples to use right? As they are both equal at the time of execution. So I now want to know is this a good way to obfuscate code or does it affect code-efficiency negatively?
Regarding obfuscation in general:
1) Against what do you want to protect?
1.1) A Java beginner understanding your code: Your approach may be ok
1.2) A Java expert understanding your code: Your approach won't really work and may not even slow the expert down by more than factor 2
1.3) A competitor understanding your code: Your approach won't really work, the competitor may put considerable resources on the task
2) Do you have to maintain the code later on?
2.1) Yes: You need something which translates your original sources to the obfuscated variants (see below)
2.2) No: You may be ok with it, however, if you need to fix a bug later on, you might not understand what you have created some time ago (it happens to experts regularly even with documented code...)
Obfuscation tools:
Having said that, you may want to look at ProGuard ( http://proguard.sourceforge.net ). It is a Java obfuscator and it even improves performance on low resources platforms (mostly by shortening class and package names and reducing the size of the class files to push around).
There are encrypting class loaders. It raises the difficulty for your opponent, but you won't be safe - see this article.
Regarding performance:
You have to run performance tests with and without your change. And you need to do that on the platform on which the software shall run eventually. Some code is certainly slower and some certainly faster - however, eventually you need to test it.

Which is the Best way to exit a method

I was looking for the ways to exit a method,
i found two methods
System.exit();
Return;
System.exit() - Exits the full program
Return exits current method and returns an error that remaining code are unreachable.
class myclass
{
public static void myfunc()
{
return;
System.out.println("Function ");
}
}
public class method_test
{
public static void main(String args[])
{
myclass mc= new myclass();
mc.myfunc();
System.out.println("Main");
}
}
There is no best way, it depends on situation.
Ideally, there is no need to exit at all, it will just return.
int a() {
return 2;
}
If there is a real need to exit, use return, there are no penalties for doing so.
void insertElementIntoStructure(Element e, Structure s) {
if (s.contains(e)) {
return; // redundant work;
}
insert(s, e); // insert the element
}
this is best avoided as much as possible as this is impossible to test for failure in voids
Avoid system.exit in functions, it is a major side effect that should be left to be used only in main.
void not_a_nice_function() {
if (errorDetected()) {
System.exit(-1);
}
print("hello, world!");
}
this pseudocode is evil because if you try to reuse this code, it will be hard to find what made it exit prematurely.
The best and proper way to exit from method is adding return statement.
System.exit() will shutdown your programm.
if you use system.exit once a thread goes there, it won't come back.
system.exit is part of Design of the Shutdown Hooks API
first of all your code will kill good programmers imagine this code Which is the Best way to exit a method this code example that how a return comes before a System.out.print(); as it becomes unreachable after the return statement lols
the command
System.exit(int status); (status=0 for Normal Exit && status=-1 for abnormal exit
is only used if you want to exactly quit your whole app whereas
the command
return;
is used to get out/return from a method
these two are different in their operations

Categories

Resources