Returning the value from the loop - java

I am doing a POC with the rabbitMQ and writing a program to add two numbers and getting the response.
The code that we wrote to retrieve the value from the queue is running infinite time( in a while loop) and a line( inside the while loop) waits for some data to be retrieved from the queue; until it gets something from queue it will not go for the next round of the while loop.
Means we are getting the value inside an infinite loop.
And I want to use this value for my next processing.
while (true)
{
QueueingConsumer.Delivery delivery1;
try
{
delivery = consumer.nextDelivery();
//The above line waits until delivery get some value
String result1 = new String(delivery1.getBody());
System.out.println("Result received-"+ result1);
}
catch (InterruptedException ie)
{
continue;
}
} // end while
Problem is that I am not able to return the value from the while loop( I want to run it infinite time).
How can I do that so the loop will continue and I will get the processed data outside loop too?

If 'processing the result' is an operation that completes quickly, then just do it inline, e.g. by calling a separate function that does the actual processing:
void mainLoop()
{
while (true)
{
QueueingConsumer.Delivery delivery1;
try
{
delivery = consumer.nextDelivery();
//The above line waits until delivery get some value
String result1 = new String(delivery1.getBody());
System.out.println("Result received-"+ result1);
processResult(result1);
}
catch (InterruptedException ie)
{
continue;
}
} // end while
}
void processResult(String result)
{
// Do whatever needs to be done with 'result'
}
If you need processing to happen concurrently with the loop, then you will need to work with multiple threads and the problem gets a bit more complicated.

What do you mean by that exactly?
If you want to stay in the same thread, just call a function (work on the one message received and than read the next).
If you need concurrency (always read, regardless whether you a re processing a message or not) use a producer/ consumer pattern.
Create one thread that
reads from the mq
posts into a (thread-safe) collection
signals that
goes back to read from the mq
Create at least one mor thread that
waits for the signal
reads (and removes) message from the (thread-safe) collection
process the message
goes back to wait for the signal
hth
Mario

Make your return value having more visibility.
So, you'll gain access to it's value

It sounds like you're referring to the yield feature which allows your function to return multiple values. As far as I know this is not supported out-of-the-box in Java but there are some projects available that implement this feature.

Related

Set free the data chunk blocked by read() from input stream?

I use getInputStream().read() to check if client has disconnected from the server. It works but the read() function, as it states in documentation, blocks the first letter of message. So instead of printing "Hello", it prints "ello". How can I make the read() function 'let go' of the first letter?
Here is the following server code to wait for input:
while(true)
{
if(socket.getInputStream().read()==-1)//if no response
break;
String msg = bufferedReader.readLine();
if(msg!=null) {
System.out.println("Received message: " + msg);
}
}
If there is no way to go around that, what's the alternative to getInputStream().read() to detect client disconnection?
The right approach is to not use the separate read() at all. Simply handle readLine() telling you the underlying connection is gone.
For a robust solution, there are two cases you should handle:
readLine() returns null; this is 'normal end of stream' and I'd expect it to happen if the client closed the connection cleanly.
readLine() throws an IOException, which you need try-catch to deal with. This can happen if the connection is terminated abruptly, possibly if the client exits without closing the connection.
It's for you to decide whether those two possibilities are treated identically, based in your program requirements.

BlockingQueue Works improperly with stringbuilder

I was trying to enqueue a set of strings with a thread (say thread1) into a BlockingQueue and write these queued items to a file with a different thread (thread2). A simple producer - consumer problem.
Thread1 :
while(condition) { queue.add(data); }
Thread2 :
while(true) { queue.take(data); //write the took data }
This whole operation works fine with the data being String. When I try to do the same operation with a StringBuilder, the results are random.
if the enqueued data is "This is my data", the output is "y data" or "is my data" or some random subset of the entire data ( sometimes the expected entire data too )
Is it the Blocking queue's nature to behave this way to stringBuilders or am i doing it wrong??

Why don't threads run consistently?

I am playing around with multithreading and came across an inconsistency when running a small snippet of code. The following code should print out 123123... but what I'm getting is
class RunnableDemo implements Runnable {
private String message;
RunnableDemo(String m) {
message = m;
}
public void run() {
try {
for (int i = 0; i < message.length(); i++) {
System.out.print(message.charAt(i));
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class TestThread {
public static void main(String args[]) throws InterruptedException {
new Thread(new RunnableDemo("1111111")).start();
new Thread(new RunnableDemo("2222222")).start();
new Thread(new RunnableDemo("3333333")).start();
}
}
Output: 123231231132123231321
Output: 123213123123213213213
Output: 123231213213231231213
What I don't get is that it run correctly the first pass through (prints '123') but then the second pass through it prints '231'. If the thread is printing a char, sleeping 1 second, then repeating. Shouldn't the pattern 123123... be consistent each time I run the code or at least follow the pattern of the first 3 chars?
The following code should print out 123123
Not necessarily. You should basically never rely on threads with no synchronization between them happening to wake up and execute in any particular order.
Let's take the very first character output: there's no guarantee that that will be 1. Yes, you're starting the thread printing 1 first, but that doesn't mean that's the first thread that will actually start executing run first - or even if it does, that doesn't mean that's the first thread that will get as far as the System.out.print call.
Given the fairly long sleep, I would expect (but ideally not rely on) the output being a sequence of 7 "chunks", where each "chunk" consists of the characters "123" in some permutation. But if you've got three threads which all go to sleep for a second at "roughly" the same time, you shouldn't expect them to necessarily wake up in the order 1, 2, 3 - and again, even if they do, one of them may pre-empt another within the loop body.
On a really, really slow machine, even that expectation would be invalid - imagine it takes a random amount of time between 0 and 20 seconds to call charAt - unlikely, but it's a feasible thought experiment. At that point, one of the threads could race ahead and finish its output before another of the threads managed to print anything.
Threads are designed to be independent - if you want them to work in a coordinated fashion, you have to specify that coordination yourself. There are plenty of tools for the job, but don't expect it to happen magically.
You can't predict what piece of program CPU runs at a time. While running some process the CPU converts the process into small pieces of work. As multiple processes are running at a time. CPU has to schedule according to scheduling algorithm implemented. So, in short, you cannot predict what CPU does next unless you programmatically synchronize the pieces of code.

Run method for all values in Array at once

I am currently trying to run multiple methods of the same method at the same time. Right now it is only doing one at a time and then sleeping once it loops through all of them. I need it to do all the values in the array at the same time via the method. Here is my current code:
public static void checkTimer(TS3Api api) {
for (String keys : admins) {
//What I need: Check Groups for all values in string AT THE SAME TIME
checkGroup(api, keys);
}
try {
//Sleep for 10 second
Thread.sleep(10000);
} catch (InterruptedException e) {
// Do nothing
}
}
Thread.sleep(10000) causes the current thread to sleep for 10 seconds. This would be the primary thread. You have not split off any threads from the primary one, so this is working as you wrote it.
Take a look through the Java documentation http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html
There are some examples of splitting off threads. This should get you on your way to a solution.
In Java 8 you can write something like:
admins.parallelStream().forEach(keys -> checkGroup(api, keys));
The number of items it will do in parallel are system dependent, however. In any case, it is unlikely you can do all of them in parallel unless your system has at least as many processors as there are items in admins, no matter what approach you take.

Change the value of a variable after N milliseconds in Java

I'm making a game in Java using Netbeans() and I want a Boolean variable takes the value of true when it is taken an item "X", the item "X" represents a character's ability which lasts "N" miliSeconds, what is the best way to do that after "N" miliSeconds the variable returns the value from false?
Now, not sure if it is my place to say, but I have a recommendation and an answer.
I would recommend building a skills/ability library. Use that to track cool downs, casting times etc. It would be more efficient overall.
As for the answer, check to see if the current time minus the time the ability was started is over 1000, then set the variable. Have this be used in a looped system such as a thread.
new Thread(new Runnable() {
try {
Thread.sleep(1000); //1 second
catch (InterruptedException annoyingCheckedException) {}
x = "foo";
}
You can start a new thread which waits a second (or however long you want it to wait) and then changes x.
The try-catch is because when sleeping, Java forces you to catch an InterruptedException which will be thrown if the thread is interrupted. In this case, you are never going to interrupt the thread so you don't need to worry about it.

Categories