How to make client sleep in the function? - java

I have a thread pool on the function that the clients calling.. to make only (n) clients execute this function upload() and the others wait.. i tried to call sleep() in the implementation of the function but it didn't work ...
note: I'm doing this to have time to see that other clients doesn't execute the function while there are (n) clients execute it...
i need fast help please ..
the code of Server:
public class Server extends UnicastRemoteObject implements ExcutorInterface
{
public Server()throws RemoteException
{
System.out.println("Server is in listening mode");
}
public static void main(String arg[]) throws InterruptedException
{
try{
LocateRegistry.createRegistry(1234);
Server p=new Server();
Naming.bind("//127.0.0.1:1234/obj",p);
}catch(Exception e)
{
System.out.println("Exception occurred : "+e.getMessage());
}
}
#Override
public void executeJob() throws RemoteException {
System.out.println("Inside executeJob...");
doJob a=new doJob("req_id","usrname","pwd");
ExecutorService threadExecutor = Executors.newFixedThreadPool(2);
threadExecutor.execute(a);
threadExecutor.shutdown();
}
}
the code of doJob :
public class doJob implements Runnable {
String request_id="", usrnamee="", pswd="";
public static int i = 1;
public doJob(String request_id,String usrnamee,String pswd) {
this.request_id=request_id;
this.usrnamee=usrnamee;
this.pswd=pswd;
}
public void upload() throws InterruptedException, IOException {
Thread.sleep(1000*15);
}
public void run() {
upload();
}
}
and I call executeJob(); in the client

One suggestion is to make "threadExecutor" a static member variable of
server.
If you want only n clients then make the pool have n threads
ExecutorService threadExecutor = Executors.newFixedThreadPool(n);
Shutting down within execute method id does not seem right.
The pool should be shutdown only when you decide to shutdown the
server.
Till then it should be alive and process the client requests.
So you have to remove the shutdown and newFixedThreadPool statements
out of the executeJob method.

To elaborate on my comment, you should surround the Thread.sleep in a try/catch and make sure the thread sleeps as long as you wish it to do so. It would look something like this:
long wakeTime = new Date().getTime() + (1000 * 15);
while ((new Date()).getTime() < wakeTime) {
try {
Thread.sleep(1000*15);
} catch (InterruptedException e) {
// do nothing
}
}
I suspect your thread was waking early because of a signal perhaps because of your call to threadExecutor.shutdown() immediately after threadExecutor.execute(a). You might want to consider calling threadExecutor.awaitTermination() as well.
Edits after learning that the task never executes:
Because threadExecutor.shutdown() doesn't wait for the tasks to complete, it looks like your program is immediately exiting. You should try using threadExecutor.awaitTermination() after your call to threadExecutor.shutdown(), placing it in a loop similar to the one suggested for Thread.sleep().

Get rid of the thread pool and use a counting semaphore to control inline execution of the upload.

I hope Thread.sleep() will help you to resolve.
Also you can use wait().

Related

Java timeout function is not working for my below codes

I tried to set a 1-second time limit for my SQL query in Java, using the methods:
How to timeout a thread
public class App {
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(new Task());
try {
System.out.println("Started..");
System.out.println(future.get(1, TimeUnit.SECONDS));
System.out.println("Finished!");
} catch (TimeoutException e) {
future.cancel(true);
System.out.println("Terminated!");
}
executor.shutdownNow();
}
}
class Task implements Callable<String> {
#Override
public String call() throws Exception {
try {
// some codes to do query via SQL Server JDBC, assuming it takes 10 seconds.
ResultSet result = statement.executeQuery();
// some codes to print the query result
return "Done";
}
catch (Exception e) {
System.out.println();
e.printStackTrace();
}
}
}
However, I found that though it prints 'Terminated' after 1 second, the program keeps running and prints the query result after 10 seconds. What's the reason why it doesn't work and how to fix it?
shutdownNow doesn't actually stop a thread, it merely sends a signal (an interrupt) that the Thread can act upon. Stopping a Thread in Java is tricky because while you can just kil the thread (with Thread.stop), you really shouldn't because you have no idea what state the Thread is in and what it will leave behind.
You can find more information in the documentation.
Calling cancel on a future does not guarantee that the job will be cancelled. It depends on the method checking periodically for interrupts, and then aborting if an interrupt is detected. Statement.execute() does not do that.
In your case, given you are executing a SQL statement, there is a method in the Statement class (setQueryTimeout) which achieves what you appear to be after without over-engineering timeouts by other means.
Another way you can approach this is by using the thread.sleep() method. I often use it when I want my program to simply pause for a short or long period of time. In the parameters, you put values in thousands that correspond to seconds. For example:
public static void main(String[] args) throws InterruptedException // Required for thread.sleep()
{
System.out.println("Hi there.");
Thread.sleep(2000); // Wait two seconds before running the next line of code
System.out.println("Goodbye.");
}
This is quite basic, but can be used for more than just strings. Hope this helps.

Java: Calling method from threads one after another

I have class Server and subclass ClientThread. ClientThread has methods receive() and broadcast(String[] msg) used to receive and send messages from/to clients connected to server.
Scheme:
public class Server extends Thread {
private ArrayList<ClientThread> clientThreads;
class ClientThread extends Thread {
public void broadcast(String[] msg) {...}
public void receive() {
...
if (msg.equals("CHANGED")) {
resumeOthers();
}
public void suspendOthers() {
for (ClientThread c: clientThreads)
if (c!=this)
try {
c.wait();
} catch (InterruptedException e) {}
}
public void resumeOthers() {
for (ClientThread c: clientThreads)
if (c!=this)
c.notify();
}
}
public void run() {
...
cmd = new String[1];
cmd[0] = "PROMPTCHANGE";
for (ClientThread currPlayer: clientThreads) {
currPlayer.broadcast(cmd);
currPlayer.suspendOthers();
}
}
}
Now, I would like to make this ClientThreads work one after another, like this:
1. ClientThread number 1 is calling method broadcast.
Now any other ClientThread existing is freezed
(they are stored in ArrayList on Server)
2. Client (another class) replies with a message that is being caught by receive()
Now this thread is freezed, and the next one starts running
Unfortunately, my approach doesn't work.
Could somebody explain me in details how to achieve that?
by calling Object.wait(), you are are suspending the CALLING thread, not the thread that this object happens to be.
so in effect, you are doing a loop that blocks the calling thread N times, definitely not what you intended.
in order to pause a thread, you need to have IT wait on an objet, or have it block entering a synchronized block (or use Thread.sleep(), but usually its not a good solution).
in other words, the client threads need to call wait, not the calling thread.
One addition:
it seems you are new to Java threading and synchronization, I strongly suggest that you read about it before attempting this.
Google around for some docs on the subject.
here is something to get you started:
http://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html
It's not clear how the sequence of execution works.
Anyway, as already said by previous answers, calling x.wait() on a Object makes the current thread block on object x. Moreover, in order to call wait() and notify(), you first have to synchronize on that object, AND, when you call wait(), you should do it in a loop, checking for an external condition, because spurious wakeups can happen.
So, the correct pattern should be something like:
void waitForCondition() {
synchronized (lockObject) {
while (!condition) {
lockObject.wait();
}
}
}
void setCondition() {
synchronized (lockObject) {
condition = true;
lockObject.notify(); //or .notifyAll()
}
}
If you want to make the threads run one after another, try http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Exchanger.html

Future.get() does not return

I have the following piece of code:
public class Test {
List<Future> future = new ArrayList<Future>();
public static void main(String args[]) throws Exception {
Adapter b1 = new Adapter();
final ExecutorService threadPool = Executors.newCachedThreadPool();
for(//iterate for number of files) {
while(data exists in file) {
//Call a function to process and update values in db
future.add(threadPool.submit(new Xyz(b1)));
//read next set of data in file;
}
}
try {
for(Future f: future) {
f.get();
}
}
catch(Exception e) {
throw e;
}
}
}
class Xyz implements Runnable {
private Adapter a1;
public Xyz(Adapter al) {
this.a1=a1;
}
#Override
public void run() {
try {
a1.abc();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
When the number of files is 1 (for loop runs for 1 time), the code runs fine.
But, when the number of files increases, the code never returns back from future.get() method.
just out of curiosity.. do i need to shutdown the executor somewhere ??
Yes, and this is likely the problem. Each Future.get() will block until the corresponding task is complete, then once all the tasks are complete your main thread will exit. But your java process will not exit because the thread pool threads are still active in the background. You should shut down the executor once you have finished with it, most likely as the last thing in your main method.
I also note that you're submitting many tasks that wrap the same Adapter instance and all call its abc() method - check that there's nothing in there that will deadlock when called simultaneously in more than one thread.
Your Callable::call / Runable::run does not return. Otherwise the corresponding future would not block.
Additional executor.shutdown or future.cancel will thow an InterruptedException to stop the thread processing the object you submitted but it is up to you if to catch it or not. Your are responsible for making the jobs you submitted stop.
When you submit thousands Callables/Runnables to a CachedExecutor that it might spawn so many threads that your machine gets so slow that you think it takes forever. But you would have noticed that.
When dealing with an undefined number of parallelizable tasks i suggest to use a FixedThreadPool with not much more threads that there are cpu cores.
Edit: Therefore when you set a breakpoints at a1.abc(); and step forward you will probably find out that it never returns.

How to run a program forever in Java? Is System.in.read() the only way?

I took this code:
28 public static void main(String[] args) throws IOException {
29 HttpServer httpServer = startServer();
30 System.out.println(String.format("Jersey app started with WADL available at "
31 + "%sapplication.wadl\nTry out %shelloworld\nHit enter to stop it...",
32 BASE_URI, BASE_URI));
33 System.in.read();
34 httpServer.stop();
35 }
Does line 33 "System.in.read()" means that it will block until there is input? Will this also work when starting the Java application using UNIX rc script - not manually started from a command line?
I'd like to write a Java application to listen for HTTP connections. The application will be started automatically when the system boots (using UNIX rc scripts). It means that the application will run continuously - theoretically forever, until purposefully stopped. What is the best way to implement this in the Java main() method?
It looks like a weird black magic but following does the trick in very elegant way
Thread.currentThread().join();
As a result the current thread, main for instance, waits on join() for thread main, that is itself, to end. Deadlocked.
The blocked thread must not be a daemon thread of course.
Leaving the main method in Java does not automatically end the program.
The JVM exists if no more non-daemon threads are running. By default the only non-daemon thread is the main thread and it ends when you leave the main method, therefore stopping the JVM.
So either don't end the main thread (by not letting the main method return) or create a new non-daemon thread that never returns (at least not until you want the JVM to end).
Since that rule is actually quite sensible there is usually a perfect candidate for such a thread. For a HTTP server, for example that could be the thread that actually accepts connections and hands them off to other threads for further processing. As long as that code is running, the JVM will continue running, even if the main method has long since finished running.
#Joachim's answer is correct.
But if (for some reason) you still want to block the main method indefinitely (without polling), then you can do this:
public static void main(String[] args) {
// Set up ...
try {
Object lock = new Object();
synchronized (lock) {
while (true) {
lock.wait();
}
}
} catch (InterruptedException ex) {
}
// Do something after we were interrupted ...
}
Since the lock object is only visible to this method, nothing can notify it, so the wait() call won't return. However, some other thread could still unblock the main thread ... by interrupting it.
while (true) { ... } should go on for a pretty long time. Of course, you'll have to figure out some way of stopping it eventually.
A common trick is to have some volatile boolean running = true, then have the main loop be while (running) { ... } and define some criteria by which a thread sets running = false.
Back to Threads, thats exactly what i wanted. Btw this awesome tutorial helped me a lot.
Main.java
public class Main {
public static void main(String args[]) {
ChatServer server = null;
/*if (args.length != 1)
System.out.println("Usage: java ChatServer port");
else*/
server = new ChatServer(Integer.parseInt("8084"));
}
}
and ChatServer.java Class extends a Runnable
public class ChatServer implements Runnable
{ private ChatServerThread clients[] = new ChatServerThread[50];
private ServerSocket server = null;
private Thread thread = null;
private int clientCount = 0;
public ChatServer(int port)
{ try
{ System.out.println("Binding to port " + port + ", please wait ...");
server = new ServerSocket(port);
System.out.println("Server started: " + server);
start(); }
catch(IOException ioe)
{
System.out.println("Can not bind to port " + port + ": " + ioe.getMessage()); }
}
public void start() {
if (thread == null) {
thread = new Thread(this);
thread.start();
}
}
.... pleas continue with the tutorial
So in the main Method a Runnable is being instantiated and a new Thread as shown in
public void start() {
is being instantiated with the runnable.
That cases the JVM to continue executing the process until you quit the project or the debugger.
Btw thats the same as Joachim Sauer posted in his answere.
Java program terminates when there are no non-daemon threads running. All you need is to have one such running thread. You could do it using infinite loops but that would consume CPU cycles. The following seems like a reasonable way to do it.
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> {}); //submit a task that does what you want (in this case, nothing)
Also we can achieve the same with the ReentrantLock and call wait() on it:
public class Test{
private static Lock mainThreadLock = new ReentrantLock();
public static void main(String[] args) throws InterruptedException {
System.out.println("Stop me if you can");
synchronized (mainThreadLock) {
mainThreadLock.wait();
}
}

Using sleep() and interrupt() to reuse thread

In a swing application, I would like to re-utilize a spawned thread instead of creating a new one to serve requests. This is because the requests would be coming in short intervals of time and the cost of creating a new thread for every request could be high.
I am thinking of using the interrupt() and sleep() methods to do this as below and would like to know any potential performance problems with the code:
public class MyUtils {
private static TabSwitcherThread tabSwitcherThread = null;
public static void handleStateChange(){
if(tabSwitcherThread == null || !tabSwitcherThread.isAlive()){
tabSwitcherThread = new TabSwitcherThread();
tabSwitcherThread.start();
}
else
tabSwitcherThread.interrupt();
}
private static class TabSwitcherThread extends Thread{
#Override
public void run() {
try {
//Serve request code
//Processing complete, sleep till next request is received (will be interrupted)
Thread.sleep(60000);
} catch (InterruptedException e) {
//Interrupted execute request
run();
}
//No request received till sleep completed so let the thread die
}
}
}
Thanks
I wouldn't use sleep() and interrupt() - I'd use wait() and notify() if I absolutely had to.
However, is there any real need to do this instead of using a ThreadPoolExecutor which can handle the thread reuse for you? Or perhaps use a BlockingQueue in a producer/consumer fashion?
Java already provides enough higher-level building blocks for this that you shouldn't need to go down to this level yourself.
I think what you're looking for is a ThreadPool. Java 5 and above comes with ThreadPoolExecutor. I would suggest you use what is provided with Java instead of writing your own, so you can save yourself a lot of time and hairs.
Of course, if you absolutely has to do it the way you described (hey, sometimes business requirement make our life hard), then use wait() and notify() as Jon suggested. I would not use sleep() in this case because you have to specified timeout, and you never know when the next request will come in. Having a thread that keep waking up then go back to sleep seems a bit wasteful of CPU cycle for me.
Here is a nice tutorial about the ThreadPoolExecutor.
EDIT:
Here is some code example:
public class MyUtils {
private static UIUpdater worker = null;
private static ExecutorService exeSrv = Executors.newFixedThreadPool(1);
public static void handleStateChange(){
if(tabSwitcherThread == null || !tabSwitcherThread.isAlive()){
worker = new UIUpdater();
}
//this call does not block
exeSrv.submit(worker, new Object());
}
private static class UIUpdater implements Runnable{
#Override
public void run() {
//do server request and update ui.
}
}
}

Categories