Queue methods in Java? [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am looking to create a pattern in Java that I am not sure how to properly accomplish... right now I have other solutions but I was wondering if there was a way to accomplish this sort of pattern
MethodArray methodarray;
public QueueSimulation(Method method){
methodarray.add(method);
}
public RunSimulation(){
methodarray.runall(); // runs all the qued methods in order
}
I have many different methods with different names that I would like to queue up.
In other words I have a class for example
Player.Moveup()
Player.Attack()
Player.FallOnGround()
World.LightsOff()
I have many different methods but I want to be able to put all these methods in an array and run them all like the pattern above.

This looks like something for which you can use a single-threaded Executor with Runnables or Callables which you create as anonymous classes.
A bit of googling led me to the Executors factory which helps create a single-threaded executor.
Here is an example:
public class MethodQueueSimulator {
Collection<Callable<Void>> methodQueue = new LinkedList<>();
ExecutorService executor = Executors.newSingleThreadExecutor();
public static void main(String args[]) throws InterruptedException {
MethodQueueSimulator simulator = new MethodQueueSimulator();
simulator.QueueSimulation(new Callable<Void>() {
#Override
public Void call() throws Exception {
System.out.println("1");
return null;
}
});
// if using java 8+, you can use lambdas instead
simulator.QueueSimulation(() -> {
System.out.println("2");
return null;
});
simulator.QueueSimulation(() -> {
System.out.println("3");
return null;
});
System.out.println("Simulation starts");
simulator.RunSimulation();
System.out.println("Simulation complete");
}
public void QueueSimulation(Callable<Void> method){
methodQueue.add(method);
}
public void RunSimulation() throws InterruptedException {
executor.invokeAll(methodQueue);
// must call shutdown, else process will not exit
executor.shutdown();
}
}
Output when run:
Simulation starts
1
2
3
Simulation complete
As you can see, the events are executed in sequential order, and the call to invokeAll is blocking, which means that code execution waits for the tasks to complete before continuing, which is why "Simulation complete" is only printed at the end. Of course, this output does not prove the claim, but try it and see for yourself.
Instead of System.out.println, you would invoke your desired methods. I did not know what sort of return values your methods have, so I opted for Void as the return type of the Callables.

Related

Running a function inside a thread [duplicate]

This question already has answers here:
Callback functions in Java
(18 answers)
Closed 2 years ago.
I'm trying to run a function inside a thread, and use the data afterwards.
The obvious problem is that the main thread isn't waiting (If that's what happens)
Though a pretty simple question, searching the internet didn't provide me any solution unfortunately.
Any advice how to implement it properly?
Thread:
MainActivity.this.runOnUiThread(new Runnable() { // A new thread to get the currencies
#Override
public void run() {
jsonConversion(mMessage);
}
Function:
public void jsonConversion(String mMessage) {
try {
JSONObject srcJson = new JSONObject(mMessage); // 2 objects, rates and base
rates = srcJson.getJSONObject("rates"); // Currencies map
baseCurrency = srcJson.getString("base"); // Base currency
lastUpdate = srcJson.getString("date"); // Last update
} catch (JSONException e) {
e.printStackTrace();
}
}
Consider using callbacks in your code to achieve what you want.
letting the program wait for a thread is not good (generally) and using asynchronous threads will not achieve what you want, because you won't get the results from the thread by the time your function is called.
So, by using callbacks, you will ensure that everything will work the way you want and methods will only be called when your parameters are ready.
Have a look at this and this answers.

How to ensure only one request at the same time in Java [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I'd like to implement a call like:
public Response getContent() throws MyException
This method internally calls to a web service, but I only want one request to the web service at the same time. That is: when the first request comes, it goes to the web service. If in the meanwhile another requests arrive, it wait for the result of the first request. After the first request returns (or throws exception), all the pending requests return too (or throw exceptions). From this point, if another request comes, it goes again to the web service with the same criteria (only one web service call at the same time)
What is the best approach for implementing this in Java/Android?
Thanks
Here's a solution with a CompletableFuture that always blocks waiting for the new result. If you call get() and there is an existing result, it triggers a new fetch and blocks. If a fetch is already in progress, it joins other threads awaiting that result.
import java.util.concurrent.CompletableFuture
import java.util.concurrent.atomic.AtomicReference
class OneAtATime<out T> {
private val pending = AtomicReference(CompletableFuture<T>())
init {
startFetching(pending.get())
}
fun get(): T {
val current = pending.get()
if (!current.isDone) {
return current.get()
}
val next = CompletableFuture<T>()
return if (pending.compareAndSet(current, next)) {
startFetching(next)
next.get()
} else {
pending.get().get()
}
}
private fun startFetching(future: CompletableFuture<T>) {
TODO("Implementation must call future.complete(newContent)")
}
}
I would recommend starting to learn how a blocking queue works:
BlockingQueue
After that you can start investigating solution how to have one call at a time. One solution is to use a semaphore:
Blocking queue with a semaphore
(from the link above) snippet that applies to your case:
EDIT
public class CustomBlockingQueue {
private List<Object> queue = new LinkedList<Object>();
private int limit;
private Semaphore mutex; // for the critical section
public CustomBlockingQueue() {
this.mutex = new Semaphore(1);
}
//enqueue can be process task, etc.
private void enqueue(Object o) throws InterruptedException {
mutex.acquire(); // critical section starts
queue.add(o); //or custom operation
mutex.release(); // critical section ends
}
//as pointed out in the comments this is more queue related
private Object dequeue() throws InterruptedException {
mutex.acquire(); // critical section starts
Object o = queue.remove(0);//or custom operation
mutex.release(); // critical section ends
return o;
}
}

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 threads common questions [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 8 years ago.
Improve this question
I have some questions about java threads:
if I have a class that runs a number of threads when one thread reaches to exit(1) command line will it exit the thread or the whole application including the other threads?
2.how can I make one thread notify all other threads that run from the same class to stop?
3.does using synchronized make only one thread ,regardless his source in the code, to do this part of code?
4.if I am running a thread in java using run() if I call a method from inside the run() does this still running as a thread or it is not allowed?
1) Only if thread are daemons, application will not wait to close even if they are running.
Example: comment or not the setDaemon(true)
public class Test {
public static void main(final String[] args) {
new Launcher(parent).start();
}
public static class Launcher extends Thread {
public Launcher(final String name) {
this.setName(name);
}
#Override
public void run() {
System.err.println(getName() + is starting);
for (int i = 0; i < 10; i++) {
new Waiter(child + i).start();
}
try {
Thread.sleep(1000);
System.err.println(getName() + is no more sleeping);
} catch (final InterruptedException e) {
e.printStackTrace();
}
System.err.println(getName() + is stopping);
}
}
public static class Waiter extends Thread {
public Waiter(final String name) {
super(name);
super.setDaemon(true);
}
#Override
public void run() {
System.err.println(getName() + is starting);
try {
Thread.sleep(12000);
System.err.println(getName() + is no more sleeping);
} catch (final InterruptedException e) {
e.printStackTrace();
}
}
}
}
2) To force the stop, you can use different approach, different patterns. Sorry to not have THE solution. You can take a look at : http://docs.oracle.com/javase/7/docs/api/java/lang/ThreadGroup.html
3) Yeah, it's the goal of synchronized.
4) It depends what you do but basically, calling a method do not launch another thread, except if the methods does it.
if I have a class that runs a number of threads when one thread reaches to exit(1) command line will it exit the thread or the whole application including the other threads?
A call to System.exit(1) will terminate the calling thread and all other threads. It is the most brutal way of ending a Java program, namely completely shutting down the JVM, and should rarely be used at all.
how can I make one thread notify all other threads that run from the same class to stop?
Not at all. If you have references to the other Thread objects, you can call Thread#interrupt(), but whether or not the other threads check their interrupted status or reach a place where they may throw an InterruptedException is left to them.
does using synchronized make only one thread ,regardless his source in the code, to do this part of code?
Intuitively yes. However, when there is a wait() in this block, then the corresponding lock (that is, the object that was synchronized on) will be released and can be acquired by other threads.
if I am running a thread in java using run() if I call a method from inside the run() does this still running as a thread or it is not allowed?
When a thread calls a method, then the same thread also executes this method (silently wondering how else it should be...)

Java - Running a thread twice [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
From another post:
If a Thread needs to be run more than once, then one should make an
new instance of the Thread and call start on it.
How is this done?
I would use another layer of abstraction. Use an ExecutorService.
Here is a simple example:
public static void main(String args[]) throws InterruptedException {
final ExecutorService service = Executors.newCachedThreadPool();
final class MyTask implements Runnable {
#Override
public void run() {
System.out.println("Running my task.");
}
};
for (int i = 0; i < 10; ++i) {
service.submit(new MyTask());
}
service.shutdown();
service.awaitTermination(1, TimeUnit.DAYS);
}
Just dump your task into the service as many times as you want.
The ExecutorService is a thread pool - it has a number of Threads that take tasks as they come. This removes the overhead of spawning new Threads because it caches them.
Basically, a thread cannot be restarted.
So if you want a reusable "thread", you are really talking about a Runnable. You might do something like this:
Runnable myTask = new Runnable() {
public void run() {
// Do some task
}
}
Thread t1 = new Thread(myTask);
t1.start();
t1.join();
Thread t2 = new Thread(myTask);
t2.start();
(This is purely for illustration purposes only! It is much better to run your "runnables" using a more sophisticated mechanism, such as provided by one of the ExecutorService classes, which is going to manage the actual threads in a way that avoids them terminating.)
A java Thread cannot be run twice. Once it has been started and finished its work, it cannot be started again (calling method start will fail). So you'll have to create a new instance of Thread (using the same Runnable) and start it.

Categories

Resources