Correct Implementation of Multithreading - java

I've been thinking about this for a few days now, and I am under the belief that my thinking of how multithreading works is flawed. I've consulted the API for Concurrency, and still did not get an answer to my question.
If I have some process that I want to return a unique string, and I want 100 different threads to run this process (thereby giving me 100 threads with 100 different strings), I can utilize executorServices to accomplish this, correct?
Then, once every thread has a string, I want to send that string to a queue, thereby blasting the queue with messages (again, sounds like a usage for a executorService.submit() call).
Lastly, Once a thread sends the message to to the queue, I want this thread to immediately start checking another queue for a response (matching it's unique string), and if it matches, output some data and terminte.
Although I am under the impression that using Executorservice would be the answer to my issue, I am failing in implementation. Is there another solution that I am missing, or does multithreading using using this method suffice--and if so, how?
Code thus far. I stopped after the sendTextMessage after realizing my issue:
int arraySize = 750; //Number of hits to send out: MANIPULATE THIS IF YOU WANT TO SEND MORE
// String[] toSend = new String[arraySize];
String[] rfids = new String[arraySize];
double total = 0;
int count = 0;
//Insert Connection information and set up clients here//
clientSend.connectSend();
clientRec.connectRec(); //edit to ensure credientials are corrects
// System.out.println("Signed-in");
StringBuffer output = new StringBuffer(); //What holds out output
File infile = new File("infile.txt"); //Populating Rfids array
Scanner scan = new Scanner(infile);
for (int i = 0; i <= arraySize-1; i++)
{
if(scan.hasNextLine())
{
rfids[i]=scan.nextLine();
// System.out.println(rfids[i]);
}
}
scan.close();
count=0;
ExecutorService load = Executors.newFixedThreadPool(arraySize);
Callable<String> readAndSendPrep = () ->
{
StringBuffer fileBasedResponse = new StringBuffer();
String rfid = "";
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("input.txt")); //This is the standard message that will be sent everytime, give or take
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String line; //temp var
for(int x = 0; x<arraySize-1;x++)
{
try {
while ((line = reader.readLine ()) != null)
{
if (line.trim().startsWith("<MessageId>"))
{
// System.out.println(rf);
rfid = rfids[arraySize]; //not necessary i think
int endIndex = line.trim().indexOf("</MessageId>");
String messageId = line.trim().substring(11, endIndex);
line = "<MessageId>" + messageId + " - " + rfids[arraySize] + "</MessageId>"; //puts unique ID in thread details
}
else if (line.trim().startsWith("str"))
{
// System.out.println(allRFID[thisIndex]);
rfid = rfids[arraySize];
line = "str" + rfids[arraySize] + "str"; //Another unique ID
// System.out.println("BOOM");
}
fileBasedResponse.append(line); //put the whole response to the StringBuffer object
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Thread.sleep(1);
return fileBasedResponse.toString();
};
TimeUnit.SECONDS.sleep(10);
Future<String> fileBasedResponse = load.submit(readAndSendPrep);
while(!fileBasedResponse.isDone())
{
Thread.sleep(1);
}
String fileBasedResponseStr = fileBasedResponse.toString();
Runnable sender = () ->
{
try {
clientSend.sendTextMessage(fileBasedResponseStr);
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
clientSend.close(); //close connections
clientRec.close();
System.out.println(output.toString()); //output the results
System.out.println(count);

Related

RandomAccessFile writing non-printable characters/newlines when writing regular text to a file

I am trying to write to an existing file with RandomAccessFile, but the call to writer.writeUTF() overwrites the two characters before the write offset with non-printable characters or newlines. I genuinely do not know what is causing this problem, and I have done multiple searches which turned up nothing.
File mapObjects = new File(args[0] + "/data/maps/objects");
ArrayList<String> warpNames = new ArrayList<String>();
ArrayList<Integer> offsets = new ArrayList<Integer>();
for (File mapObject : mapObjects.listFiles()) {
try {
Scanner reader = new Scanner(mapObject);
int offset = 0;
String ln = new String();
System.out.println(mapObject.getPath());
while (!ln.contains("def_warps_to")) { // will loop until it finds the definition of the warp name
offset += ln.length();
ln = reader.nextLine();
}
offset += 28;
warpNames.add(ln.substring(14)); // adds the "warps_to" token to the list
offsets.add(offset);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Collections.shuffle(warpNames); // randomize
for (String s : warpNames)
System.out.println(s);
int i = 0; // iterator of warpNames and offsets
for (File mapObject : mapObjects.listFiles()) {
try {
RandomAccessFile writer = new RandomAccessFile(mapObject, "rw");
writer.seek(offsets.get(i));
writer.writeUTF(warpNames.get(i)); // overwrites "warps_to" token with randomized one
i++;
} catch (IOException e) {
e.printStackTrace();
}
}
I fixed it, all I had to do was call
writer.writeBytes(warpNames.get(i))
instead of
writer.writeUTF(warpNames.get(i))

Is there a faster way to use csv reader in Java?

I need to open a csv file in more parts, each one by 5,000 samples and then plot them. To go back and forward on the signal each time I click a button I have to instantiate a new reader and than I skip to the point I need. My signal is big, is about 135,000 samples so csvReader.skip() method is very slow when I work with last samples. But to go back I can't delete lines, so each time my iterator needs to be re-instantiated. I noticed that skip uses a for loop? Is there a better way to overtake this problem? Here is my code:
public void updateSign(int segmento) {
Log.d("segmento", Integer.toString(segmento));
//check if I am in the signal length
if (segmento>0 && (float)(segmento-1)<=(float)TOTAL/normaLen)
{
try {
reader = new CSVReader(new FileReader(new File(patty)));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
List<Integer> sign = new ArrayList<>();
//this is the point of the signal where i finish
int len = segmento * normaLen;
//check if i am at the end of the signal
if (len >= TOTAL) {
len = TOTAL;
segmento=0;
avanti.setValue(false);
System.out.println(avanti.getValue());
} else {
lines = TOTAL - len;
avanti.setValue(true);
System.out.println(avanti.getValue());
}
//the int to i need to skip
int skipper = (segmento-1)*normaLen;
try {
System.out.println("pre skip");
reader.skip(skipper);
System.out.println("post skip");
} catch (IOException e) {
e.printStackTrace();
}
//my iterator
it = reader.iterator();
System.out.println("iteratore fatto");
//loop to build my mini-signal to plot
//having only 5,000 sample it is fast enaugh
for (int i = skipper; i < len-1; i++) {
if (i>=(segmento-1)*normaLen) {
sign.add(Integer.parseInt(it.next()[0]));
}
else
{
it.next();
System.out.println("non ha funzionato lo skip");
}
}
System.out.println("ciclo for: too much fatica?");
//set sign to be plotted by my fragment
liveSign.setValue(sign);
}
}
Thanks in advance!

I cant access rtf file after saving something in it

Just at it says in the title, I can save something inside the rtf file sometimes(my save function is a working progress). Im using a mac, and i cant save as a txt. I do not know if this is normal or not and I having troubles with it since I dont know why but I get an arrayoutofbounds error when I try to use the line Player p = new Player(splitLine[0], splitLine[1], splitLine[2]);
Here is my read and write code.
final String FILE_PATH = "/Users/macbookair/Desktop/comp sci ia/TypingPractice/Player records.rtf";
BufferedReader reader;
PrintWriter writer;
Player[] readRecords() {
// This is called by AppLogic.load() which runs when the AppLogic is
// instantiated.
// The array of Person objects that we create from the load file
// This holds the current line from the load file
String nextLine;
// This is a two-element array that holds name/surname once it has
// been split at the # sign
String[] splitLine = new String[4];
for(int i=0; i< splitLine.length;i++){
splitLine[i] = "0";
}
// This is just a counter of how many lines I've read in
int count = 0;
try {
reader = new BufferedReader(new FileReader(FILE_PATH));
// Get the first line
nextLine = reader.readLine();
// Loop until we've been through every line in the file
while (nextLine != null) {
// Split the current line at the # sign
splitLine = nextLine.split("#");
Player p = new Player(splitLine[0], splitLine[1], splitLine[2]);
// Put it in the array
playerArray[count] = p;
// Increment the counter
count = count + 1;
// Get the next line
nextLine = reader.readLine();
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
void writeRecords(Player[] p) {
try {
writer = new PrintWriter(new FileWriter(FILE_PATHPhrase));
// Loop through each Person in the Person array
for (int i = 0; i < p.length; i++) {
// Write the name, then a # sign, then the surname
writer.println(p[i].getWPM() + "#" + p[i].getMistakes() + "#" + p[i].getTime());
}
} catch (Exception e) {
e.printStackTrace();
}
writer.close();
}

Trying to save a clone of an array in a txt file but returns NULL

I am making an app that keeps username and scores from a game in a txt file. The concept is that when it writes a new username and score to the txt file it should open the .txt file, read it and then make a clone of it adding a new uername and score entry in the txt file.
I am thinking of making this with 2 object arrays. The first is the one that is read in and the new will be the one is writen which will have one more entry.
So if player[i] is readen player[i+1] should be writen with new entry.
I am giving u the code below!
private Player[] myplayer=null;
private Player[] mynewplayer=null;
//open Players.txt
int i;
int n;
String filename="players.txt";
try
{
FileReader fp=new FileReader(filename);
BufferedReader bf=new BufferedReader(fp);
n=Integer.parseInt(bf.readLine());
myplayer=new Player[n];
int x=n+1;
mynewplayer=new Player[x];
for(i=0;i<n;i++)
{
String s=bf.readLine();
String user="",score="";
user=s.substring(0,s.indexOf(","));
s=s.substring(s.indexOf(",")+1);
score=s;
myplayer[i]=new Player(user,Double.parseDouble(score));
for(i=0;i<n;i++)
{
mynewplayer[i]= myplayer[i];
}
mynewplayer[x]=new Player(Username,Double.parseDouble(score));
}
bf.close();
fp.close();
}catch(IOException e)
{
System.out.println("Exception was "+e.getMessage());
}
//----------------------------------WRITE mytxt!-------------
n=myplayer.length;
try
{
filename="players.txt";
FileWriter fp=new FileWriter(filename);
fp.write(""+n+"\n");
for(i=0;i<n+1;i++)
fp.write(""+mynewplayer[i]+"\n");
fp.close();
}catch(IOException e)
{
System.out.println("Exception was "+e.getMessage());
}
//----------------------------------WRITE mytxt!-----------
//Get on Message
String s="";
for(i=0;i<mynewplayer.length;i++)
s=s+mynewplayer[i]+"\n";
JOptionPane.showMessageDialog(null,"Players are \n "+s);
Problem is that when it's written, it returns null for mynewplayer.
I suppose the mynewplayer doesnt really take the entries of the "myplayer" but neither writes the new username.
Compile doesnt show any errors. Just writes NULL to the textfile.
Ask me if u want further info on the code writen!
Thanks in advance!
Here is an edited version of your code, with some improvements and there should be a comment around code that I changed, explaining what I did.
Player[] myPlayer = null; // first word uncapitalized, every
Player[] myNewPlayer = null; // other word begins with a capital
//open Players.txt
int i, n; // combine the variables into 1 line
String filename = "players.txt";
try {
FileReader fp = new FileReader(filename);
BufferedReader bf = new BufferedReader(fp);
n = Integer.parseInt(bf.readLine());
// not needed
//myPlayer = new Player[n];
// NOT NEEDED int x = n + 1;
myNewPlayer = new Player[n + 1];
for (i = 0; i < n; i++) {
String s = bf.readLine();
String user, score; // combine variables, doesnt need to initalize them
String[] items = s.split(","); // Splits the line into array elements on every delimiter -> ,
//user = s.substring(0, s.indexOf(","));
//s = s.substring(s.indexOf(",") + 1);
//score = s;
user = items[0];
score = items[1];
// this line below isnt actually needed
//myPlayer[i] = new Player(user, Double.parseDouble(score));
// Create a new player clone, dont copy the previous one
myNewPlayer[i] = new Player(user, Double.parseDouble(score));
}
// We've read all the variables from the text file, now we create the last one
// Since myNewPlayer is (n+1) size, the range of the array is
// 0 to n
// the last index will be n New Score Variable
myNewPlayer[n] = new Player("Username variable", Double.parseDouble("22"));
bf.close();
fp.close();
} catch (IOException e) {
System.out.println("Exception was " + e.getMessage());
}
//----------------------------------WRITE mytxt!-------------
// This is called a ternary operator
// it is a 1 line if statement
// the format is like so
// booleanLogic ? trueAnswer Execution : falseAnswer Execution;
// if () { true }else { false }
n = myNewPlayer != null ? myNewPlayer.length : 0;
// CHANGED HERE - was using the first array rather than second
// dont need the 1st array
try {
filename = "players.txt";
FileWriter fp = new FileWriter(filename);
// Dont need "" before the items
fp.write(n + "\n");
for (i = 0; i < n; i++) {
fp.write(myNewPlayer[i] + "\n");
}
fp.close();
} catch (IOException e) {
System.out.println("Exception was " + e.getMessage());
}
//----------------------------------WRITE mytxt!-----------
//Get on Message
String s = "";
for (i = 0; i < myNewPlayer.length; i++) {
// s += ""; is like doing s = s + "";
s += myNewPlayer[i] + "\n";
}
JOptionPane.showMessageDialog(null, "Players are \n " + s);
I believe that your problem is this:
for(i=0;i<n;i++)
{
String s=bf.readLine();
String user="",score="";
user=s.substring(0,s.indexOf(","));
s=s.substring(s.indexOf(",")+1);
score=s;
myplayer[i]=new Player(user,Double.parseDouble(score));
for(i=0;i<n;i++)
{
mynewplayer[i]= myplayer[i];
}
mynewplayer[x]=new Player(Username,Double.parseDouble(score));
}
You have nested loops, which is fine, but they use the same counter (the variable i ).
So what is happening is the first line of the file is read, and then added to myplayer[0]. However, instead of just also adding it to mynewplayer[0], you start another loop on i. This loop:
for(i=0;i<n;i++)
{
mynewplayer[i]= myplayer[i];
}
is going to copy the first player into mynewplayer[0]...and then null into every other entry (since myplayer only has the firsdt element filled.
The problem is that after that loop completes, i will equal n, so when you get back to the top of the outer loop, the check $i
Perhaps what you should do is this:
for(i=0;i<n;i++)
{
String s=bf.readLine();
String user="",score="";
user=s.substring(0,s.indexOf(","));
s=s.substring(s.indexOf(",")+1);
score=s;
myplayer[i]=new Player(user,Double.parseDouble(score));
mynewplayer[i]= new Player(user,Double.parseDouble(score));
}
mynewplayer[x]=new Player(<the new username>,Double.parseDouble(<the new score>));

why cant this bubble sort this list in java to output alphabetically?

What variables am I supposed to use with this bubble sort? I tried many times to look up tutorials online but, they all mainly showed how to do this with a smaller list of numbers and not a scanned string file. I just need to have two flight routes considered equal if they have the same source and destination airport code and if they are not equal, the comparison should be made based on the source airport code alphabetically. I really need help on this one its hurting my brain and I know this solution is probably extremely simple. I went ahead and highlighted the code for bubble sorting that needs help.
public class FlightRouteDriver
{
public static void main(String[] args)
{
String routeFile = "FlightRouteData-US.txt";
#SuppressWarnings("rawtypes")
ArrayList<Comparable> flRouteList = new ArrayList<Comparable>();
BufferedReader br = null;
String line = "";
try {
br = new BufferedReader(new FileReader(routeFile));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
while ((line = br.readLine()) != null) {
String[] dataSet = line.split(";");
FlightRoute flRoute = createFlightRoute(dataSet);
flRouteList.add(flRoute);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Uploaded data file contains " + flRouteList.size() + " flight routes.");
//sorting list of flight route
System.out.println("Bubble Sort Algorithm running ..." );
BubbleSort(flRouteList);
System.out.println("Flight route data sorted..." );
//Getting user input on source and destination airport codes
Scanner userInput = new Scanner(System.in);
System.out.println("Enter Departure Airport code: ");
String departureAirport = userInput.next();
System.out.println("Enter Destination Airport code: ");
String destinationAirport = userInput.next();
userInput.close();
//creating a target flight for search
String[] target = new String[13];
target[0]="";
target[1]="0";
target[2]=departureAirport;
target[3]="";
target[4]="01:00";
target[5]="0";
target[6]=destinationAirport;
target[7]="";
target[8]="01:00";
target[9]="0";
target[10]="N";
target[11]="0";
target[12]="";
FlightRoute targetRoute = createFlightRoute(target);
ArrayList<Comparable> found = linearSearch (flRouteList, targetRoute);
System.out.println("\n***Flight Route search result***");
if(found == null)
System.out.println("Flight route not found.");
else
{
for (int i = 0; i<found.size(); i++)
System.out.println("Flight Routes found. Details are below.\n" + found.get(i));
}
}//end of main method
// -------------------------------------------------------------------
// Creates a FlightRoute object using specified String array object.
// -------------------------------------------------------------------
private static FlightRoute createFlightRoute(String[] dataSet)
{
String airline = dataSet[0];
int airlineID = Integer.parseInt(dataSet[1]);
String sourceAirportCode = dataSet[2];
String sourceAirportCity = dataSet[3];
Time sourceCityDepartureTime = Time.valueOf(dataSet[4]+":00");
int sourceAirportID = Integer.parseInt(dataSet[5]);
String destinationAirportCode = dataSet[6];
String destinationAirportCity = dataSet[7];
Time destinationCityArrivalTime = Time.valueOf(dataSet[8]+":00");
int destinationAirportID = Integer.parseInt(dataSet[9]);
char codeshare = dataSet[10].charAt(0);
int stops = Integer.parseInt(dataSet[11]);
String equipment = dataSet[12];
FlightRoute flRoute = new FlightRoute(airline,airlineID,sourceAirportCode,
sourceAirportCity,sourceCityDepartureTime, sourceAirportID,
destinationAirportCode,destinationAirportCity, destinationCityArrivalTime,
destinationAirportID,codeshare, stops, equipment );
return flRoute;
}//end of createFlightRoute method
// -------------------------------------------------------------------
// Sorts the specified list of objects using a bubble sort algorithm.
// -------------------------------------------------------------------
static void BubbleSort(ArrayList<Comparable> flRouteList) {
String t;
for(int i=0; i<flRouteList.length; i++) {
for(int j=0; j<flRouteList.length-1-i; j++) {
if(Comparable[j].compareTo(dataSet[j+1])>0) {
t= array[j];
array[j] = array[j+1];
array[j+1] = t;
}
}
}
}

Categories

Resources