Sockets blocking with inconsistent recieved messages - java

I'm writing test for my chat-client system which works with sockets and 1 server. I have created 3 sockets(each one in thread representing client) which choose chat-room( "USA room") and all send 1 message, here is what I do-start the server, wait all clients to come in the room, each send a message, then read all messages from each socket,shutdown server, however while reading some socket's messages the test freezes. This freezing is caused by this line: String line = reader.readLine();. Some sockets receive the right amount of messages (which is 5), others just freeze with messages less than 5. I can't figure why the socket freeze.
public class ChatTest {
final int NUMBER_OF_SOCKETS = 3;
Server server = new Server();
Map<String, Socket> mapSockets = new ConcurrentSkipListMap<>();
List<String> socketMessages = new CopyOnWriteArrayList<>();
List<Thread> allThreads = new CopyOnWriteArrayList<>();
List<Socket> allsockets = new CopyOnWriteArrayList<>();
Set<Set<String>> allSets = new HashSet<>();
Map<Thread, Socket> mapThreadSocket = new ConcurrentHashMap<>();
private final CyclicBarrier barrier = new CyclicBarrier(NUMBER_OF_SOCKETS);
Thread t = new Thread(new Runnable() {
#Override
public void run() {
server.start();
}
});
#BeforeSuite(alwaysRun = true)
public void startServer() {
t.start();
}
#AfterSuite(alwaysRun = true)
public void stopServer() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
server.stop();
}
Thread t2 = new Thread() {
#Override
public void run() {
try {
final List<String> linesFromFile = ChatSystemUtils.readFromFile(ClientTestDataConstants.TestDataFile.toString(), 50);
System.out.println("all client threads have entered room called USA room ");
for (int i = 0; i < NUMBER_OF_SOCKETS; i++) {
final PrintWriter stream = new PrintWriter(allsockets.get(i).getOutputStream(), true);
mapSockets.put(linesFromFile.get(i), allsockets.get(i));
stream.println(linesFromFile.get(i));
socketMessages.add(i, linesFromFile.get(i));
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < NUMBER_OF_SOCKETS; i++) {
final BufferedReader reader = new BufferedReader(new InputStreamReader(allsockets.get(i).getInputStream()));
System.out.println("AT NEW USER");
Set<String> userMessages = new HashSet<>();
for (int j = 0; j < 5; j++) {
String line = reader.readLine();
System.out.println(line);
if (j > NUMBER_OF_SOCKETS) {
String msg = line.substring(9, line.length());
userMessages.add(msg);
}
}
userMessages.add(socketMessages.get(i));
}
} catch (IOException e) {
e.printStackTrace();
}
}
};
#Test
public void testMessagesReceived() throws IOException {
List<Thread> threadList = new LinkedList<>();
for (int i = 0; i < NUMBER_OF_SOCKETS; i++) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
barrier.await();
} catch (InterruptedException | BrokenBarrierException e1) {
e1.printStackTrace();
}
try {
Socket socket = new Socket("127.0.0.1", 3000);
allsockets.add(socket);
final PrintWriter stream = new PrintWriter(socket.getOutputStream(), true);
stream.println("USA room");
} catch (IOException e) {
e.printStackTrace();
}
}
};
Thread t = new Thread(r);
threadList.add(t);
}
for (int i = 0; i < threadList.size(); i++) {
threadList.get(i).start();
}
for (int i = 0; i < threadList.size(); i++) {
try {
threadList.get(i).join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
t2.start();
try {
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("most of the times we don't get here ");
}
}
Server class :
public final class Server {
public static boolean stopServerCalled;
private final int port;
private final String host;
private final Map<String, ChatRoom> mapRooms = ChatServerUtils.getChatRooms();
private final AtomicInteger clientID = new AtomicInteger(1);
private ServerSocket serverSocket;
private List<IClient> clientsPickingRoom;
private final ExecutorService executorService = Executors.newCachedThreadPool();
public Server() {
final Properties prop = new Properties();
try (final InputStream inputStream = getClass()
.getResourceAsStream("/com/egt/chat/server/ChatServerConfig.properties")) {// read from a file of
// properties
prop.load(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
this.port = Integer.parseInt(prop.getProperty("port"));
this.host = prop.getProperty("host");
this.clientsPickingRoom = new CopyOnWriteArrayList<>();
}
public void start() {
try {
final InetAddress address = InetAddress.getByName(host);
serverSocket = new ServerSocket(port, 50, address);
System.out.println("Listening on socket : " + serverSocket);
while (!Thread.currentThread().isInterrupted()) {
final Socket newSocket = serverSocket.accept();
System.out.println("Connection established with: " + newSocket);
final ClientContainer newClient = new ClientContainer(clientID.get(), newSocket);
executorService.execute(new ClientContainerRunnable(newClient, this));
clientID.incrementAndGet();
clientsPickingRoom.add(newClient);
}
} catch (IOException e) {
System.out.println("Server stopped!");
}
}
}

PrintWriter stream = new PrintWriter(allsockets.get(i).getOutputStream(), true);
stream.println(linesFromFile.get(i));
Isn't writing to this client socket, it's sending a message out to the server it's connected to. Where is the server writing the 5 lines to each client socket, which you read here:
for (int i = 0; i < NUMBER_OF_SOCKETS; i++) {
final BufferedReader reader = new BufferedReader(new InputStreamReader(allsockets.get(i).getInputStream()));
for (int j = 0; j < 5; j++) {
String line = reader.readLine();
System.out.println(line);
// ...
It may be best if you dump all your code, then I could actually help. As it is, you aren't really helping me help you.

Related

Cannot invoke "java.net.ServerSocket.close()" because "Server.server" is null

I'm trying to write a simple client/server application. I have a data on a client's side, that turns into an integer array and transfers to server. The server makes the calcutaions and returns them to client. But my program falls with this exception.
Sorry for long text, I'm just studying and really need your help.
public class Client {
private static Socket clientSocket;
private static ObjectInputStream in;
private static ObjectOutputStream out;
private static int[] parsedValue;
public Client(String input) {
try {
parsedValue = Arrays.stream(input.split(",")).mapToInt(Integer::parseInt).toArray();
} catch (Exception e) {
e.printStackTrace();
}
}
public Client(int[] input) {
parsedValue = input;
}
public Client(List<Integer> input) {
try {
parsedValue = input.stream().mapToInt(d->d).toArray();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
try {
clientSocket = new Socket("localhost", 4004);
in = new ObjectInputStream(clientSocket.getInputStream());
out = new ObjectOutputStream(clientSocket.getOutputStream());
String clientTestString = "440,5,16";
Client stringClient = new Client(clientTestString);
out.writeObject(stringClient.parsedValue);
out.flush();
System.out.println(in.readObject());
int[] clientIntsTest = {39, 10, 5};
Client arrayClient = new Client(clientIntsTest);
out.writeObject(arrayClient.parsedValue);
out.flush();
System.out.println(in.readObject());
List<Integer> clientsTestList = Arrays.asList(781, 9, 7);
Client listClient = new Client(clientsTestList);
out.writeObject(listClient.parsedValue);
out.flush();
System.out.println(in.readObject());
} finally {
System.out.println("Client was closed");
clientSocket.close();
in.close();
out.close();
}
} catch (IOException | ClassNotFoundException e) {
System.err.println(e);
}
}
}
public class Server {
private static Socket clientSocket;
private static ServerSocket server;
private static ObjectInputStream in;
private static ObjectOutputStream out;
private static int[] parsedValue;
public String getResult() {
return calculation(parsedValue);
}
public String calculation(int[] parsedValue) {
parsedValue[0] = toDecimal(parsedValue[0], parsedValue[1]);
String answer = "";
int temp = 0;
String digits = new String("ABCDEF");
while (parsedValue[0] > 0) {
temp = parsedValue[0] % parsedValue[2];
if (temp < 10) {
answer = temp + answer;
} else {
answer = digits.charAt(temp - 10) + answer;
}
parsedValue[0] /= parsedValue[2];
}
return answer;
}
public int toDecimal(int value, int baseNotation) {
int i = 0;
int decimalNumber = 0;
if (value > 0) {
while (value != 0) {
decimalNumber += (value % 10) * Math.pow(baseNotation, i);
value /= 10;
i++;
}
}
return decimalNumber;
}
public static void main(String[] args) {
try {
try {
server = new ServerSocket(4004);
System.out.println("Server runs");
clientSocket = server.accept();
try {
in = new ObjectInputStream(clientSocket.getInputStream());
out = new ObjectOutputStream(clientSocket.getOutputStream());
parsedValue = (int[]) in.readObject();
System.out.println(parsedValue);
Server examp = new Server();
String answer = examp.getResult();
System.out.println(answer);
out.writeObject(answer);
out.flush();
} finally {
clientSocket.close();
in.close();
out.close();
}
} finally {
System.out.println("Server closed");
server.close();
}
} catch (IOException | ClassNotFoundException e) {
System.err.println(e);
}
}
}
In this two lines
Server examp = new Server();
String answer = examp.getResult();
you cretat a new object which overriddes the field private static ServerSocket server;
A better solution is to put the logic from your main() into a seperate method like run(), instantiate in main() a new object of server and call the run() on it. Dont't forget to make all fields as instance members by removing the static keyword.
public static void main(String[] args) {
Server examp = new Server();
examp.run();
}
public void run() {
try {
try {
server = new ServerSocket(4004);
System.out.println("Server runs");
clientSocket = server.accept();
try {
in = new ObjectInputStream(clientSocket.getInputStream());
out = new ObjectOutputStream(clientSocket.getOutputStream());
parsedValue = (int[]) in.readObject();
System.out.println(parsedValue);
String answer = getResult();
System.out.println(answer);
out.writeObject(answer);
out.flush();
} finally {
clientSocket.close();
in.close();
out.close();
}
} finally {
System.out.println("Server closed");
server.close();
}
} catch (IOException | ClassNotFoundException e) {
System.err.println(e);
}
}
By the way: You should always use this patern to get out of the 'static-trap'. So I suggest you refactor your Client calss too.

Can't download using Sockets java

I have kinda figured out how sockets work but I seem to have run into another wall. I'm supposed to somehow use the socket to transfer the data, but how? when I try it gives me a SocketException bind, saying it's already in use. I used it originally to connect it to a Directory, where I will gather other nodes and then if one doesn't have the data, it will ask for it from the other nodes.
class Download extends Thread {
CloudByte[] list = new CloudByte[1000000];
#Override
public void run() {
try {
var nodes = ConnectingDirectory.getNodes();
for (Nodes node : nodes) {
if ((node.getHostPort() == ConnectingDirectory.getHostIP())) {
downloadFile(node.getHostPort());
}
}
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
try {
fileWriting(getFile().getName(), list);
} catch (IOException e) {
e.printStackTrace();
}
}
public synchronized void downloadFile(int port) throws IOException, ClassNotFoundException {
while (true) {
ServerSocket ss = ConnectingDirectory.getServerSocket();
Socket socket = ss.accept();
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
for (int j = 0; j <= 9999; j += 1) {
byte[] bit = (byte[]) ois.readObject();
for (int i = 0; i < bit.length; i++) {
list[i + j * 100] = new CloudByte(bit[i]);
}
}
System.out.println("Download Completed");
}
}
This is the function, I'm using to Download the date from the InputStream, the problem I'm having is that it's not downloading unless I restart the other Node. Is there a way to avoid having to do that? I really am at a loss.
Note; the for is because I need to transfer 1000000 bytes, in packets of 100 bytes.
The sending the data is:
class Upload extends Thread {
#Override
public void run() {
if (getFile().exists()) {
var nodes = ConnectingDirectory.getNodes();
for (Nodes node : nodes) {
if (node.getHostPort() == ConnectingDirectory.getHostIP()) {
try {
uploadFile(node.getHostPort());
} catch (IOException e) {
e.printStackTrace();
}
}
}
} else {
new Download().start();
}
}
public static void uploadFile(int hostPort) throws IOException {
Socket socket = new Socket("localhost", hostPort);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
ByteBlockRequest bbr = new ByteBlockRequest(getStoredData());
for (int j = 0; j <= 9999; j += 1) {
objectOutputStream.writeObject(bbr.blocksToSend(j));
}
objectOutputStream.flush();
System.out.println("Uploaded all the Data!");
}
Creating the server socket:
public ConnectingDirectory(String hostName, int hostIP, int directoryIP) throws IOException {
this.hostName = hostName;
this.directoryIP = directoryIP;
ConnectingDirectory.hostIP = hostIP;
this.address = InetAddress.getByName(hostName);
socket = new Socket(address, directoryIP);
serverSocket = new ServerSocket(hostIP);
signUp();
askConnectedNodes();
}

Multithread Server and Client with sockets in Java

I am trying to create for a university project a server / slave / client project.
The server should open 2 ports, one port will be for the connection of the slave and another port for the client.
I have setup 2 threads 1 for the client and another for the slave. The client should sent random numbers to server and server should forward randomly those numbers to slave instances. The slave should check if the current number exist on their list and if it's not available to store it, otherwise they should sent a message to server that the number already exist.
Then I created the client thread which consist of 2 threads, one for sending the numbers to server and another thread to read messages coming from the server.
There is something wrong with the code of the PrintWriter, I cannot make it to send the numbers to server when the code is inside the thread. If I move the code on the main and cancel the thread the messages are being sent without any issue.
What could be the issue for this?
Below is the current code from server (master) and the client.
public class Client {
private static final int NUMBERS = 50;
private static final int AMPLITUDE = 100;
private static int masterPort;
public Client(int port) {
this.masterPort = port;
}
public static void main(String[] args) throws IOException{
String serverHostname = "127.0.0.1";
System.out.println("Αναμονή για σύνδεση στον σέρβερ " + serverHostname + " στην πόρτα 30091.");
Socket echoSocket = null;
BufferedReader in = null;
try {
echoSocket = new Socket(serverHostname, 18889);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Δεν μπορεί να πραγματοποιηθεί σύνδεση με τον σέρβερ: " + serverHostname);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: " + serverHostname);
System.exit(1);
}
ClientOut clientOut = new ClientOut(echoSocket);
clientOut.start();
ClientIn clientIn = new ClientIn(in);
clientIn.start();
in.close();
echoSocket.close();
}
public static class ClientOut extends Thread {
private PrintWriter out;
public ClientOut(Socket echoSocket) throws IOException {
this.out = new PrintWriter(echoSocket.getOutputStream(), true);
}
#Override
public void run() {
System.out.println("Ο client συνδέθηκε!");
Random rnd = new Random();
try {
for (int i=0; i<NUMBERS; i++) {
int num = rnd.nextInt(AMPLITUDE);
System.out.println(num);
out.println(num);
TimeUnit.SECONDS.sleep(1);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
out.close();
}
}
public static class ClientIn extends Thread {
private BufferedReader in;
public ClientIn(BufferedReader in) {
this.in = in;
}
#Override
public void run() {
}
}
}
public class Master {
private int slavePort;
private int clientPort;
private SlaveThread slaveThread;
private ClientThread clientThread;
private boolean running = false;
public static int slaveConnected; // Slave connection counter
public Master(int slavePort, int clientPort) {
this.slavePort = slavePort;
this.clientPort = clientPort;
this.slaveConnected = 0;
public void startServer() {
try {
this.slaveThread = new SlaveThread(slavePort);
this.clientThread = new ClientThread(clientPort);
System.out.println( "Αναμονή για σύνδεση client / slave" );
slaveThread.start();
clientThread.start();
} catch (IOException e) {
e.printStackTrace();
}
}
public void stopServer() {
running = false;
this.slaveThread.interrupt();
this.clientThread.interrupt();
}
class SlaveThread extends Thread {
private ServerSocket slaveSocket;
SlaveThread(int slavePort) throws IOException {
this.slaveSocket = new ServerSocket(slavePort);
}
#Override
public void run() {
running = true;
while (running) {
try {
// Call accept() to receive the next connection
Socket slSocket = slaveSocket.accept();
System.out.println("Δημιουργήθηκε μια νέα σύνδεση Slave");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class ClientThread extends Thread {
private ServerSocket clientSocket;
ClientThread(int clientPort) throws IOException {
this.clientSocket = new ServerSocket(clientPort);
}
#Override
public void run() {
running = true;
while (running) {
try {
Socket clSocket = clientSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(clSocket.getInputStream()));
System.out.println("Δημιουργήθηκε μια νέα σύνδεση Client");
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("Client: " + inputLine);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
Master server = new Master( 30091, 18889);
server.startServer();
// Automatically shutdown in 1 minute
try {
Thread.sleep( 60000 );
} catch(Exception e) {
e.printStackTrace();
}
server.stopServer();
}
I found the solution.
The Socket should be created on the Client Thread constructor and not to be passed as reference.
So the client should be
public class Client {
private static final int NUMBERS = 50;
private static final int AMPLITUDE = 100;
private static int masterPort;
public Client(int port) {
this.masterPort = port;
}
public static void main(String[] args) throws IOException{
String serverHostname = "127.0.0.1"; //Ορίζουμε την διεύθυνση που είναι ο σέρβερ
System.out.println("Αναμονή για σύνδεση στον σέρβερ " + serverHostname + " στην πόρτα 30091.");
ClientOut clientOut = new ClientOut(serverHostname);
clientOut.start();
ClientIn clientIn = new ClientIn(serverHostname);
clientIn.start();
}
public static class ClientOut extends Thread {
private Socket echoSocket;
private PrintWriter writer;
ClientOut(String serverHostname) throws IOException {
this.echoSocket = new Socket(serverHostname, 18889);
this.writer = new PrintWriter(echoSocket.getOutputStream(), true);;
}
#Override
public void run() {
System.out.println("Ο client συνδέθηκε!");
Random rnd = new Random();
try {
for (int i=0; i<NUMBERS; i++) {
int num = rnd.nextInt(AMPLITUDE);
System.out.println(num);
writer.println(num);
TimeUnit.SECONDS.sleep(1);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
writer.close();
}
}

Show stage before initialize controller in JavaFx

I made this server which works but only show itself when a client try to establish a connection. If I execute it alone, it runs without showing any anything. This is the main file:
public class Server extends Application {
#Override
public void start(Stage stage) throws Exception {
FXMLLoader sLoader = new FXMLLoader(getClass().getResource("server.fxml"));
BorderPane root = new BorderPane(sLoader.load());
ServerController sController = sLoader.getController();
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
sController.initModel();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
And this is its controller:
public class ServerController {
#FXML
private TextArea textarea;
public void initModel() {
try {
int i = 1;
ServerSocket s = new ServerSocket(5000);
//while (true) {
Socket incoming = s.accept(); //is waiting for connections
textarea.setText("Waiting for connections");
Runnable r = new ThreadedEchoHandler(incoming, i);
new Thread(r).start();
i++;
//}
} catch (IOException e) {
e.printStackTrace();
}
}
class ThreadedEchoHandler implements Runnable {
private Socket incoming;
private int counter;
/**
* Constructs a handler.
*
* #param i the incoming socket
* #param c the counter for the handlers (used in prompts)
*/
public ThreadedEchoHandler(Socket in, int c) {
incoming = in;
counter = c;
}
public void run() {
textarea.setText("Connected from: " + incoming.getLocalAddress());
String nomeAccount = "";
try {
//PHASE 1: The server receives the email
try {
BufferedReader in = new BufferedReader(new InputStreamReader(incoming.getInputStream()));
nomeAccount = in.readLine();
} catch (IOException ex) {
System.out.println("Not works");
}
//PHASE 2: I'm getting all the emails from the files
File dir = new File("src/server/" + nomeAccount);
String[] tmp = new String[100];
int i = 0;
for (File file : dir.listFiles()) {
if (file.isFile() && !(file.getName().equals(".DS_Store"))) {
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
tmp[i++] = line;
}
} catch (IOException ex) {
System.out.println("Cannot read from file");
}
}
}
//PHASE 3: The server sends the ArrayList to the client
PrintWriter out = new PrintWriter(incoming.getOutputStream(), true);
for (int j = 0; j < i; j++)
out.println(tmp[j]); // send the strings name to client
} catch (IOException ex) {
System.out.println("Cannot send the strings to the client");
} finally {
try {
incoming.close();
} catch (IOException ex) {
System.out.println("Cannot closing the socket");
}
}
}
}
}
I'm trying to follow the MVC pattern and I don't know if I should separate the part where I'm waiting for connections from the initialize method.
EDIT:the textarea.setText("Waiting for connections"); also doesn't work, I guess its because the textarea still not exists when the compiler reach that part

Synchronized method() running only 1 thread till end from a poll of several

This is a project I'm trying to do for University.
I'm making an app using sockets to connect several Clients to a Server.
When I get a new connection a new instance of ServerHandler is called that listens to the port for requests from the Client.
This is my ServerHandler class
public class ServerHandler implements Runnable {
private Socket clientSocket;
private Server server;
ArrayList<Thread> threads = new ArrayList<Thread>();
ArrayList<News> news = new ArrayList<News>();
ArrayList<News> filteredNews = new ArrayList<>();
private int iterator = 0;
private boolean available = true;
private boolean finished = false;
public ServerHandler(Socket clientSocket, Server server) {
this.clientSocket = clientSocket;
this.server = server;
this.news = server.getListNews();
}
#Override
public void run() {
System.out.println("Hello!");
while(true) {
try {
System.out.println("Waiting for input");
BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String str = br.readLine();
System.out.println(str);
new Thread(new Runnable() {
#Override
public void run() {
try {
manageMessages();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void manageMessages() throws IOException, InterruptedException {
System.out.println("Button Search.");
launchThreads(str);
for(Thread t : threads) {
t.join();
}
filteredNews.sort(null);
System.out.println("News have been filtered and sorted.");
System.out.println("Sending info to Client.");
sendtoClient();
System.out.println("Sent info to Client.");
}
}).start();
} catch (IOException e) {
System.out.println("Socket closed" + e);
break;
}
}
}
When I get a request I launch a new Thread responsible of returning something to the Client.
My problem comes from the launchThreads(String str) method.
This method is meant to create and add 10 threads to an Array of Threads.
Each Thread then is going to run through the same ArrayList of News in search of a word (String str, sent by the Client).
All threads are supposed to share the work, that is searching for the String str through every single News in the shared ArrayList<News>.
private void launchThreads(String str) {
System.out.println("Lauching threads");
filteredNews.clear();
threads.clear();
finished = false;
available = true;
iterator = 0;
for(int i = 0; i < 10; i++) {
threads.add(new Thread(new Runnable(){public void run(){try {
queueThreads(str);
filterNews(str);
} catch (InterruptedException e) {
e.printStackTrace();
}}}));
threads.get(i).start();
}
System.out.println("Launched threads: " + threads.size());
}
private synchronized void queueThreads(String str) throws InterruptedException {
while(!available && !finished) {
System.out.println("Waiting.");
wait();
}
System.out.println("Gone through.");
available = false;
}
private synchronized void filterNews(String str) throws InterruptedException {
int contador = 0;
if(iterator < news.size()) {
String temp = news.get(iterator).getTitle() + " " + news.get(iterator).getBody();
String[] tempArray = temp.replaceAll("[^a-zA-Z ]", "").split("\\s+");
for(String word : tempArray) {
if(word.equalsIgnoreCase(str)) {
contador++;
}
}
if(contador > 0) {
News n = new News(news.get(iterator).getTitle(),news.get(iterator).getBody(), contador);
n.setTitle(contador + " - " + n.getTitle());
System.out.println(news.get(iterator).toString());
filteredNews.add(n);
}
iterator++;
}else {
finished = true;
}
available = true;
notifyAll();
queueThreads(str);}
What I'm getting is that only 1 Thread runs the whole search while the other ones just stay waiting until I change the finished flag to 'true', that is set when the search ends.
I would love to get some help on how can I launch several threads to run through the array sharing work between them.
Thanks in advance.

Categories

Resources