I tried to implement multithreading in Java by using executor service approach. Here is my code:
public class GetResponseContentWithExecutorService {
private static final int MYTHREADS = 30;
public static void main(String args[]) throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(MYTHREADS);
String[] urlList ={"url1", "url2", "url3" ...};
for (int i = 0; i < urlList.length; i++) {
String baseUrl = "myUrl";
Runnable worker = new MyRunnable(baseUrl, urlList[i].split("-")[0], urlList[i].split("-")[1]);
executor.execute(worker);
}
executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println("\nCompleted all threads");
}
}
public class MyRunnable implements Runnable {
private final String baseUrl;
private final String a;
private final String b;
MyRunnable(String baseUrl, String a, String b) {
this.baseUrl = baseUrl;
this.a= a;
this.b= b;
}
#Override
public void run() {
String result = "";
int code = 200;
try {
URL siteURL = new URL(baseUrl + a + b);
HttpURLConnection connection = (HttpURLConnection) siteURL.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(3000);
connection.connect();
code = connection.getResponseCode();
if (code == 200) {
result = "-> Succ<-\t" + "Code: " + code;
} else {
result = "-> NoSuc <-\t" + "Code: " + code;
}
}
catch (Exception e) {
result = e.getMessage();
}
System.out.println(code);
}
}
The thing is that for about 30 urls I need to wait approx.40seconds and I would like to make it way faster. Any suggestions to what am I doing wrong here?
Any help is appreciated!!
Related
MessageCreator: Encapsulate and resolve ports and device unique identifiers.
public class MessageCreator {
private static final String HEADER_PORT = "to port:";
private static final String HEADER_SN = "My sn:";
public static String buildWithPort(int port) {
return HEADER_PORT + port;
}
public static int parsePort(String data) {
if (data.startsWith(HEADER_PORT)) {
return Integer.parseInt(data.substring(HEADER_PORT.length()));
}
return -1;
}
public static String buildWithSn(String sn) {
return HEADER_SN + sn;
}
public static String parseSn(String data) {
if (data.startsWith(HEADER_SN)) {
return data.substring(HEADER_SN.length());
}
return null;
}
}
UdpProvider: Loop to listen to a specific port, then parse the received data, determine whether the data conforms to the predetermined format, get the sender's response port from it, and respond with the uniquely identified UUID value to the UDP searcher.
public class UdpProvider {
public static void main(String[] args) throws IOException {
String sn = UUID.randomUUID().toString();
Provider provider = new Provider(sn);
provider.start();
// Warning: Result of 'InputStream.read()' is ignored
System.in.read();
provider.exit();
}
private static class Provider extends Thread {
private DatagramSocket ds = null;
private boolean done = false;
private final String sn;
public Provider(String sn) {
super();
this.sn = sn;
}
#Override
public void run() {
super.run();
try {
ds = new DatagramSocket(20000);
while (!done) {
final byte[] buf = new byte[512];
DatagramPacket receivePak = new DatagramPacket(buf, buf.length);
ds.receive(receivePak);
String ip = receivePak.getAddress().getHostAddress();
int port = receivePak.getPort();
byte[] receivePakData = receivePak.getData();
String receiveData = new String(receivePakData, 0, /*receivePakData.length*/receivePak.getLength());
System.out.println("received from -> ip: " + ip + ", port: " + port + ", data: " + receiveData);
int responsePort = MessageCreator.parsePort(receiveData.trim());
if (responsePort != -1) {
String responseData = MessageCreator.buildWithSn(sn);
byte[] bytes = responseData.getBytes(StandardCharsets.UTF_8);
DatagramPacket responsePak = new DatagramPacket(bytes, bytes.length,
/*InetAddress.getLocalHost()*/
receivePak.getAddress(),
responsePort);
ds.send(responsePak);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close();
}
}
public void exit() {
done = true;
close();
}
public void close() {
if (ds != null) {
ds.close();
ds = null;
}
}
}
}
UdpSearcher: Listening to a specific port and sending a LAN broadcast, sending a broadcast sets the listening port in the data, so you need to turn on listening first to finish before you can send a broadcast, and once you receive the response data, you can parse the device information
public class UdpSearcher {
private static final int LISTENER_PORT = 30000;
public static void main(String[] args) throws IOException, InterruptedException {
Listener listener = listen();
sendBroadcast();
// Warning: Result of 'InputStream.read()' is ignored
System.in.read();
List<Device> deviceList = listener.getDevicesAndClose();
for (Device device : deviceList) {
System.out.println(device);
}
}
public static void sendBroadcast() throws IOException {
DatagramSocket ds = new DatagramSocket();
String sendData = MessageCreator.buildWithPort(LISTENER_PORT);
byte[] sendDataBytes = sendData.getBytes(StandardCharsets.UTF_8);
DatagramPacket sendPak = new DatagramPacket(sendDataBytes, sendDataBytes.length);
sendPak.setAddress(InetAddress.getByName("255.255.255.255"));
sendPak.setPort(20000);
ds.send(sendPak);
ds.close();
}
public static Listener listen() throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(1);
Listener listener = new Listener(LISTENER_PORT, countDownLatch);
listener.start();
countDownLatch.await();
return listener;
}
private static class Listener extends Thread {
private final int listenPort;
private DatagramSocket ds = null;
private boolean done = false;
private final CountDownLatch countDownLatch;
private List<Device> devices = new ArrayList<>();
public Listener(int listenPort, CountDownLatch countDownLatch) {
super();
this.listenPort = listenPort;
this.countDownLatch = countDownLatch;
}
#Override
public void run() {
super.run();
countDownLatch.countDown();
try {
ds = new DatagramSocket(listenPort);
while (!done) {
final byte[] buf = new byte[512];
DatagramPacket receivePak = new DatagramPacket(buf, buf.length);
ds.receive(receivePak);
String ip = receivePak.getAddress().getHostAddress();
int port = receivePak.getPort();
byte[] data = receivePak.getData();
String receiveData = new String(data, 0, /*data.length*/receivePak.getLength());
String sn = MessageCreator.parseSn(receiveData);
System.out.println("received from -> ip: " + ip + ", port: " + port + ", data: " + receiveData);
if (sn != null) {
Device device = new Device(ip, port, sn);
devices.add(device);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close();
}
}
public void close() {
if (ds != null) {
ds.close();
ds = null;
}
}
public List<Device> getDevicesAndClose() {
done = true;
close();
return devices;
}
}
private static class Device {
private String ip;
private int port;
private String sn;
public Device(String ip, int port, String sn) {
this.ip = ip;
this.port = port;
this.sn = sn;
}
#Override
public String toString() {
return "Device{" +
"ip='" + ip + '\'' +
", port=" + port +
", sn='" + sn + '\'' +
'}';
}
}
}
UdpProvider and UdpSearcher worked fine and printed corrresponding data until I input a char sequence from keyboard follwed by pressing Enter key on each console window, both threw an exception on this line ds.receive(receivePak); :
I am trying to restrict the amount of clients on my server,so i just sending message from my server when it is full and print it in my client by ending process for him.But as i use multiple threads i cant stop my writeMessage thread
Tried AtomicBoolean,but i didnt work
public class Client {
private static final Logger LOGGER = LogManager.getLogger();
private BufferedReader consoleReader;
private String name;
private String address;
private int port;
private Thread writeMessage, readMessage;
private ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of("UTC"));
private LocalTime dTime = zonedDateTime.toLocalTime();
private Net net;
private AtomicBoolean running = new AtomicBoolean(true);
public Client(String address, int port) {
this.address = address;
this.port = port;
net = new Net(address, port);
consoleReader = new BufferedReader(new InputStreamReader(System.in));
printName();
readMessage();
writeMessage();
}
private void printName() {
System.out.println("Print your name:");
try {
name = consoleReader.readLine();
while (NameValidator.nameIsValid(name)) {
System.out.println("Name should contain more than 1 letter");
name = consoleReader.readLine();
}
net.send(name + "\n");
} catch (IOException e) {
LOGGER.error(e);
}
}
private void readMessage() {
readMessage = new Thread(() -> {
String str = net.receive();
while (net.isConnected()) {
if ("full".equals(str)) {
System.out.println("server is full");
running.set(false);
break;
} else {
System.out.println(str);
str = net.receive();
}
}
net.offService();
}, "readMessage");
readMessage.start();
}
private void writeMessage() {
writeMessage = new Thread(() -> {
while (running.get()) {
String userWord;
try {
String time = dTime.getHour() + ":" + dTime.getMinute() + ":" + dTime.getSecond();
userWord = consoleReader.readLine();
if (userWord.equals("quit")) {
net.send(userWord + "\n");
ClientAmountGenerator.decrement();
running.set(false);
} else {
net.send("(" + time + ") " + name + " says : " + userWord + "\n");
}
} catch (IOException e) {
LOGGER.error(e);
}
}
net.offService();
}, "writeMessage");
writeMessage.start();
}
}
I want to change running to "false",so the writeMessage thread wont work if it gets message "full" from the server
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
In the first method, I just want to create a thread for each URL in the array and parse it:
public void readFriendData(String[] urls) {
Thread[] urlThreads = new Thread[urls.length];
for (int x = 0; x < urls.length; x++) {
Runobject input = new Runobject(urls[x], this);
Thread one = new Thread(input);
urlThreads[x] = one;
}
for(int x = 0; x< urls.length; x++){
urlThreads[x].start();
}
}
And then I made a separate class for my runnable object, where the run method creates a bufferedReader to scan the html file and parses it.
package twitbook;
public class Runobject implements Runnable {
public String address;
public Twitbook net;
public Runobject(String theAdress, Twitbook net) {
address = theAdress;
this.net = net;
}
#Override
public void run() {
try {
URL url = new URL(address);
URLConnection urlConnection = url.openConnection();
BufferedReader scanner = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream()));
String input = scanner.readLine();
while (!input.equals("</body>")) {
if (input.startsWith("<tr> <td>addperson</td>")) {
input.replaceAll("<tr> <td>addperson</td>", "");
input.replaceAll(" <td>", "");
input.replaceAll("</td> </tr>", "");
net.addUser(input);
} else if (input.startsWith("<tr> <td>addfriend</td>")) {
String[] bits = new String[2];
input.replaceAll("<tr> <td>addfriend</td>", "");
bits = input.split("</td> <td>");
input.replaceAll(" <td>", "");
input.replaceAll("</td> </tr>", "");
net.friend(bits[0], bits[1]);
net.friend(bits[1], bits[0]);
}
input = scanner.readLine();
}
scanner.close();
} catch (IOException e) {
System.out.println("bad URL");
}
}
}
I know when the first method is called, even though I started the threads, it doesn't go through the run method in the runObject class. Why is this?
Your code works perfectly. You simply do not realize it. Add few logging/output messages and you will see it. Oh, by the way, anticipate end of input. Here is simplified code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class Runobject implements Runnable {
public String address;
public static void main(String a[]) {
System.out.println("Start");
readFriendData(new String[] { "http://google.com", "http://yahoo.com" });
System.out.println("End");
}
public static void readFriendData(String[] urls) {
Thread[] urlThreads = new Thread[urls.length];
for (int x = 0; x < urls.length; x++) {
Runobject input = new Runobject(urls[x]);
Thread one = new Thread(input);
urlThreads[x] = one;
}
for (int x = 0; x < urls.length; x++) {
urlThreads[x].start();
}
}
public Runobject(String theAdress) {
address = theAdress;
System.out.println(address);
}
#Override
public void run() {
try {
URL url = new URL(address);
URLConnection urlConnection = url.openConnection();
BufferedReader scanner = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream()));
int countOfLines = 0;
String input = scanner.readLine();
while (input != null && !input.equals("</body>")) {
countOfLines++;
if (input.startsWith("<tr> <td>addperson</td>")) {
input.replaceAll("<tr> <td>addperson</td>", "");
input.replaceAll(" <td>", "");
input.replaceAll("</td> </tr>", "");
// net.addUser(input);
} else if (input.startsWith("<tr> <td>addfriend</td>")) {
String[] bits = new String[2];
input.replaceAll("<tr> <td>addfriend</td>", "");
bits = input.split("</td> <td>");
input.replaceAll(" <td>", "");
input.replaceAll("</td> </tr>", "");
// net.friend(bits[0], bits[1]);
// net.friend(bits[1], bits[0]);
}
input = scanner.readLine();
}
scanner.close();
System.out.println(address + " has " + countOfLines + " lines");
} catch (IOException e) {
System.out.println("bad URL");
}
}
}
and here is output:
Start
http://google.com
http://yahoo.com
End
http://google.com has 8 lines
http://yahoo.com has 63 lines
Pay attention that your main thread is already finished when your readers just started yet. One word - multithreading.
Though, I don't like the quality of it. I know I am not code reviewer. Please try this!
public static void main(String[] args) {
Twitbook twitbook = new Twitbook();
String[] urls = new String[2];
urls[0] = "www.google.com";
urls[0] = "www.yahoo.com";
twitbook.readFriendData(urls);
}
public void readFriendData(String[] urls) {
CountDownLatch latch = new CountDownLatch(urls.length);
for (int x = 0; x < urls.length; x++) {
Runobject input = new Runobject(urls[x], this, latch);
input.run();
}
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
return;
}
public synchronized void addUser(String input) {
return;
}
public synchronized void friend(String bits1, String bits2) {
return;
}
RunObject class here
public class Runobject implements Runnable {
public String address;
public Twitbook net;
public CountDownLatch latch;
public Runobject(String theAdress, Twitbook net, CountDownLatch latch) {
address = theAdress;
this.net = net;
}
#Override
public void run() {
try {
URL url = new URL(address);
URLConnection urlConnection = url.openConnection();
BufferedReader scanner = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream()));
String input = scanner.readLine();
while (!input.equals("</body>")) {
if (input.startsWith("<tr> <td>addperson</td>")) {
input.replaceAll("<tr> <td>addperson</td>", "");
input.replaceAll(" <td>", "");
input.replaceAll("</td> </tr>", "");
net.addUser(input);
} else if (input.startsWith("<tr> <td>addfriend</td>")) {
String[] bits = new String[2];
input.replaceAll("<tr> <td>addfriend</td>", "");
bits = input.split("</td> <td>");
input.replaceAll(" <td>", "");
input.replaceAll("</td> </tr>", "");
net.friend(bits[0], bits[1]);
net.friend(bits[1], bits[0]);
}
input = scanner.readLine();
}
scanner.close();
} catch (IOException e) {
System.out.println("bad URL");
} finally {
latch.countDown();
}
}
Please consider better design. These links may help you to do better coding.
Thread pool is a good option.
http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html
CountDownLatch for finish all threads http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CountDownLatch.html
Runobject can be a private inner class as well.
Wait until child threads completed : Java
disclaimer :- Answered with help of other question and answers.
I have a Jframe form class like this
public class LoginForm extends javax.swing.JFrame
In this,i get username & password from user and then send it to php server for validation and
will get the response as OK or Invalid User. I have another class named 'public class LoginTimer implements Runnable' . In this class i have some code to execute. I want that in 'LoginForm' when i got response as OK, the control will move to second class 'LoginTimer' means second class will be
called. please tell me how to do it??
=====================================================================
private void sendGet(String username,String pwd) throws Exception
{
String url = "http://localhost/login.php?username="+username+ "&password="+pwd;
final String USER_AGENT = "Mozilla/5.0";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null)
{
response.append(inputLine);
}
in.close();
//print result
String r=response.toString();
System.out.println("String "+r);
if(r.equals("OK"))
{
System.out.println("you are a valid user");
}
else
{
System.out.println("You are an invalid user");
}
}
Below is my code for LoginTimer class. In this, I am getting names of visible windows and then thread starts and in run() method i call sendGet() method for sending window names to php server page. I want that when I got the OK response in LoginForm class,the LoginTimer class will be called and executed automatically.I mean, when user logged in & verified then sending of window names to php server will start automatically.
public class LoginTimer implements Runnable
{
LoginTimer lk1;
String s3;
static int arraySize=10;
static int arrayGrowth=2;
static String[] m=new String[arraySize];
static int count=0;
#Override
public void run()
{
for(int ck=0;ck<3;ck++)
{File file=new File("G:\\check.txt");
Scanner scanner = null;
try
{
scanner = new Scanner(file);
}
catch (FileNotFoundException ex)
{
Logger.getLogger(LoginTimer.class.getName()).log(Level.SEVERE, null, ex);
}
while(scanner.hasNext())
{
String[] tokens = scanner.nextLine().split(":");
String last = tokens[1];
// System.out.println(last);
if(last!=null)
{
try
{
lk1.sendGet(last,m);
}
catch (Exception ex)
{
Logger.getLogger(LoginTimer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
Logger.getLogger(LoginTimer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public static void main(String[] args)
{
(new Thread(new LoginTimer())).start();
final List<WindowInfo> inflList=new ArrayList<WindowInfo>();
final List<Integer> order=new ArrayList<Integer>();
int top = User32.instance.GetTopWindow(0);
while (top!=0)
{
order.add(top);
top = User32.instance.GetWindow(top, User32.GW_HWNDNEXT);
}
User32.instance.EnumWindows(new WndEnumProc()
{
public boolean callback(int hWnd, int lParam)
{
if (User32.instance.IsWindowVisible(hWnd))
{
RECT r = new RECT();
User32.instance.GetWindowRect(hWnd, r);
if (r.left>-32000)
{ // minimized
byte[] buffer = new byte[1024];
User32.instance.GetWindowTextA(hWnd, buffer, buffer.length);
String title = Native.toString(buffer);
//lk1.getid(title);
if (m.length == count)
{
// expand list
m = Arrays.copyOf(m, m.length + arrayGrowth);
}
m[count]=Native.toString(buffer);
System.out.println("title===="+m[count]);
count++;
inflList.add(new WindowInfo(hWnd, r, title));
}
}
return true;
}
}, 0);
Collections.sort(inflList, new Comparator<WindowInfo>()
{
public int compare(WindowInfo o1, WindowInfo o2)
{
return order.indexOf(o1.hwnd)-order.indexOf(o2.hwnd);
}
});
for (WindowInfo w : inflList)
{
System.out.println(w);
}
}
public static interface WndEnumProc extends StdCallLibrary.StdCallCallback
{
boolean callback (int hWnd, int lParam);
}
public static interface User32 extends StdCallLibrary
{
final User32 instance = (User32) Native.loadLibrary ("user32", User32.class);
boolean EnumWindows (WndEnumProc wndenumproc, int lParam);
boolean IsWindowVisible(int hWnd);
int GetWindowRect(int hWnd, RECT r);
void GetWindowTextA(int hWnd, byte[] buffer, int buflen);
int GetTopWindow(int hWnd);
int GetWindow(int hWnd, int flag);
final int GW_HWNDNEXT = 2;
}
public static class RECT extends Structure
{
public int left,top,right,bottom;
}
public static class WindowInfo
{
int hwnd;
RECT rect;
String title;
public WindowInfo(int hwnd, RECT rect, String title)
{
this.hwnd = hwnd; this.rect = rect; this.title = title;
}
public String toString()
{
return String.format("(%d,%d)-(%d,%d) : \"%s\"",
rect.left ,rect.top,rect.right,rect.bottom,title);
}
}
public static void sendGet(String last1,String[] get) throws Exception
{
for(int t=0;t<get.length;t++)
{
if(get[t]!=null)
{
String url = "http://localhost/add_windows.php?username="+last1+"&windowname="+get[t];
final String USER_AGENT = "Mozilla/5.0";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null)
{
response.append(inputLine);
}
in.close();
String r=response.toString();
System.out.println("String "+r);
}
}
}
}
As u are implementing runnable class you are creating thread. So create an object of LoginTimer as
LoginTimer lt = new LoginTimer();
in LoginForm class after you get result from php page.
Now call
lt.start();
after ur creation of object ; which will call ur run method of thread.
Now in ur LoginTimer class override the run method like
class LoginTimer implements Runnable
{
public void run()
{
//put your code which you want to execute now ...
}
}
As your class implements java.lang.Runnable.
To have the run() method executed by a thread, pass an instance of your class_implementing_Runnable to a Thread in its constructor.Something like
Thread thread = new Thread(new LoginTimer());
thread.start();
In my application,i have activeMq to send the message from client to server and vice versa.I run it as a standalone server.So when a client machine sends the message,the messages are passed in the activeMq queue and then retrieve by the server(my Application) if and only if the transaction is done locally,meaning the client machine and server(my application) live in the same computer. But when i run the client and server from two different computer meaning server in one and client in another then the client can only establish connection to the server but the messages are not passed to the activeMq queue.I think this is something with activeMq problem.
can anyone tell me how to solve this?
thanks
here is the code which passes the data sent by client to the queue.
package event.activeMq;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.console.command.store.amq.CommandLineSupport;
import org.apache.activemq.util.IndentPrinter;
public class ProducerTool extends Thread {
private Destination destination;
private int messageCount = 1;
private long sleepTime;
private boolean verbose = true;
private int messageSize = 1000;
private static int parallelThreads = 1;
private long timeToLive;
private String user = ActiveMQConnection.DEFAULT_USER;
private String password = ActiveMQConnection.DEFAULT_PASSWORD;
private String url = ActiveMQConnection.DEFAULT_BROKER_URL;
private String subject = "CLOUDD.DEFAULT";
private boolean topic;
private boolean transacted;
private boolean persistent;
private static Object lockResults = new Object();
private static String DateTime="";
private static String TaskID="";
private static String UniqueEventID="";
private static String Generator="";
private static String GeneratorBuildVsn="";
private static String Severity="";
private static String EventText="";
private static String SubsystemID="";
private static String EventNumber="";
private static String atmId="";
public void element(String[] element) {
this.DateTime = element[0];
this.TaskID = element[1];
this.Generator = element[2];
this.Severity = element[3];
this.EventText = element[4];
this.SubsystemID = element[5];
this.EventNumber = element[6];
this.GeneratorBuildVsn = element[7];
this.UniqueEventID = element[8];
this.atmId = element[9];
}
public static void main(String[] args) {
System.out.println("came here");
ArrayList<ProducerTool> threads = new ArrayList();
ProducerTool producerTool = new ProducerTool();
producerTool.element(args);
producerTool.showParameters();
for (int threadCount = 1; threadCount <= parallelThreads; threadCount++) {
producerTool = new ProducerTool();
CommandLineSupport.setOptions(producerTool, args);
producerTool.start();
threads.add(producerTool);
}
while (true) {
Iterator<ProducerTool> itr = threads.iterator();
int running = 0;
while (itr.hasNext()) {
ProducerTool thread = itr.next();
if (thread.isAlive()) {
running++;
}
}
if (running <= 0) {
System.out.println("All threads completed their work");
break;
}
try {
Thread.sleep(1000);
} catch (Exception e) {
}
}
}
public void showParameters() {
System.out.println("Connecting to URL: " + url);
System.out.println("Publishing a Message with size " + messageSize + " to " + (topic ? "topic" : "queue") + ": " + subject);
System.out.println("Using " + (persistent ? "persistent" : "non-persistent") + " messages");
System.out.println("Sleeping between publish " + sleepTime + " ms");
System.out.println("Running " + parallelThreads + " parallel threads");
if (timeToLive != 0) {
// System.out.println("Messages time to live " + timeToLive + " ms");
}
}
public void run() {
Connection connection = null;
try {
// Create the connection.
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url);
connection = connectionFactory.createConnection();
connection.start();
// Create the session
Session session = connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE);
if (topic) {
destination = session.createTopic(subject);
} else {
destination = session.createQueue(subject);
}
// Create the producer.
MessageProducer producer = session.createProducer(destination);
if (persistent) {
producer.setDeliveryMode(DeliveryMode.PERSISTENT);
} else {
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
}
if (timeToLive != 0) {
producer.setTimeToLive(timeToLive);
}
// Start sending messages
sendLoop(session, producer);
// System.out.println("[" + this.getName() + "] Done.");
synchronized (lockResults) {
ActiveMQConnection c = (ActiveMQConnection) connection;
// System.out.println("[" + this.getName() + "] Results:\n");
c.getConnectionStats().dump(new IndentPrinter());
}
} catch (Exception e) {
// System.out.println("[" + this.getName() + "] Caught: " + e);
e.printStackTrace();
} finally {
try {
connection.close();
} catch (Throwable ignore) {
}
}
}
protected void sendLoop(Session session, MessageProducer producer) throws Exception {
for (int i = 0; i < messageCount || messageCount == 0; i++) {
TextMessage message = session.createTextMessage(createMessageText(i));
if (verbose) {
String msg = message.getText();
if (msg.length() > 50) {
msg = msg.substring(0, 50) + "...";
}
// System.out.println("[" + this.getName() + "] Sending message: '" + msg + "'");
}
producer.send(message);
if (transacted) {
// System.out.println("[" + this.getName() + "] Committing " + messageCount + " messages");
session.commit();
}
Thread.sleep(sleepTime);
}
}
private String createMessageText(int index) {
StringBuffer buffer = new StringBuffer(messageSize);
buffer.append("DateTime "+DateTime+" EventNumber "+EventNumber+" TaskID "+TaskID+" AtmId "+atmId+
" Generator "+Generator+" GeneratorBuildVsn "+GeneratorBuildVsn+" Severity "+Severity+
" UniqueEventID "+UniqueEventID+" EventText "+EventText+" SubsystemID "+SubsystemID+" End ");
if (buffer.length() > messageSize) {
return buffer.substring(0, messageSize);
}
for (int i = buffer.length(); i < messageSize; i++) {
buffer.append(' ');
}
DateTime="";
EventNumber="";
TaskID="";
atmId="";
Generator="";
GeneratorBuildVsn="";
Severity="";
UniqueEventID="";
EventText="";
SubsystemID="";
return buffer.toString();
}
public void setPersistent(boolean durable) {
this.persistent = durable;
}
public void setMessageCount(int messageCount) {
this.messageCount = messageCount;
}
public void setMessageSize(int messageSize) {
this.messageSize = messageSize;
}
public void setPassword(String pwd) {
this.password = pwd;
}
public void setSleepTime(long sleepTime) {
this.sleepTime = sleepTime;
}
public void setSubject(String subject) {
this.subject = subject;
}
public void setTimeToLive(long timeToLive) {
this.timeToLive = timeToLive;
}
public void setParallelThreads(int parallelThreads) {
if (parallelThreads < 1) {
parallelThreads = 1;
}
this.parallelThreads = parallelThreads;
}
public void setTopic(boolean topic) {
this.topic = topic;
}
public void setQueue(boolean queue) {
this.topic = !queue;
}
public void setTransacted(boolean transacted) {
this.transacted = transacted;
}
public void setUrl(String url) {
this.url = url;
}
public void setUser(String user) {
this.user = user;
}
public void setVerbose(boolean verbose) {
this.verbose = verbose;
}
}
you need to update your questin with answers on this questions:
What os do you use?
Do you have a firewall like software on pc?
Could you provide here ActiveMQ conf file?
Could you provide a function
which implemented connection establishment?
upd:
I do't understand all your logic but i thk bug here:
try {
Thread.sleep(1000);
} catch (Exception e){
e.printStackTrace();
}
And never never never catch all exceptions! it's very dangerous.
if you want to catch exception, you need to handle it.