Here is what I am trying to do. I have a number of threads which should all wait at a common point before they proceed, so obvious solution is to use CyclicBarrier. But I want to also compute the total time taken by the threads to execute. I defined the following utility method in class ConcurrentExecutionActionTimer.
public static long elapsedTimeUsingCyclicBarrier(Executor executor, int concurrency, final Runnable action) throws InterruptedException
{
final Runnable barrierAction = new Runnable() {
#Override
public void run() {
System.out.println("Condition of barrier is met.");
}
};
final
CyclicBarrier barrier = new CyclicBarrier(concurrency, barrierAction);
final CountDownLatch done = new CountDownLatch(concurrency);
for(int i=0; i<concurrency; i++ ){
executor.execute(new Runnable() {
#Override
public void run() {
try {
System.out.println("Waiting at barrier.");
barrier.await();
action.run();
//Cyclic barrier gets reset automatically. Again wait for them to finish.
barrier.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (BrokenBarrierException e) {
e.printStackTrace();
} finally {
done.countDown();
}
}
});
}
long startNanoTime = System.nanoTime();
done.await();
return System.nanoTime() - startNanoTime;
}
Then I called it up like:
public static void main(String[] args) {
//Executor is replacement for common thread idiom: (new Thread(r)).start() to e.execute(r)
ExecutorService executor = Executors.newFixedThreadPool(10);
Worker action = new Worker();
int concurrency = 5;
try {
long elapsedTime = ConcurrentExecutionActionTimer.elapsedTimeUsingCyclicBarrier(executor, concurrency, action);
double seconds = (double)elapsedTime / 1000000000.0;
System.out.println("Time Taken approximately: " + seconds + "seconds.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Here Worker is suppose my thread that does some work. For example:
class Worker implements Runnable {
#Override
public void run() {
System.out.println("Doing work.");
for(int i=0; i<20; i++) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Finished.");
}
}
As I wanted to print the time taken I had to use CountDownLatch to make sure the control does not return back to main before all the threads are finished. Do we have any other way to make sure the same functionality?
You should use the same CyclicBarrier instance. The only difference is that you make the cyclic barrier count be #threads + 1. You can then use that barrier to calculate the time it took all of the threads to complete. The start time is calculated when the first barrier has been reached and the end time is calculated when the second barrier has been reached. This way you know approximately when all the threads have been started and when all of them have completed.
Therefore this:
long startNanoTime = System.nanoTime();
done.await();
return System.nanoTime() - startNanoTime;
becomes:
barrier.await()
long startNanoTime = System.nanoTime();
barrier.await();
return System.nanoTime() - startNanoTime;
import java.io.*;
import java.util.*;
import java.util.concurrent.CyclicBarrier;
class BusLine {
private String destination;
protected static int max_seat, checkpoint;
private ArrayList<Bus> BUSA = new ArrayList<Bus>();
private ArrayList<Bus> BUSC = new ArrayList<Bus>();
private ArrayList<Group> GROUP_A = new ArrayList<Group>();
private ArrayList<Group> GROUP_C = new ArrayList<Group>();
public BusLine(int ms, int cp, String d) {
max_seat = ms;
checkpoint = cp;
destination = d;
}
public String getDestination() {
return destination;
}
public void printAirportCheckpoint() {
System.out.println();
System.out.printf("%s >> %d airport-bound buses have been allocated.", Thread.currentThread().getName(), BUSA.size());
}
public void printCityCheckpoint() {
System.out.println();
System.out.printf("%s >> %d city-bound buses have been allocated.", Thread.currentThread().getName(), BUSC.size());
System.out.println();
System.out.println();
}
public void BusBoundA() {
int temp = 0;
for (int i = 0; i < BUSA.size(); i++) {
if (BUSA.get(i).getName().equals("A" + i)) {
temp++;
}
}
System.out.println();
System.out.printf("%s >> ==== Airport Bound ====", Thread.currentThread().getName());
System.out.println();
for (int i = 0; i < temp; i++) {
System.out.printf("%s >> %s : ", Thread.currentThread().getName(), "A" + i);
for (int j = 0; j < GROUP_A.size(); j++) {
if (GROUP_A.get(j).getBusname().equals("A" + i)) {
System.out.printf(" %-20s(%2d seats)", GROUP_A.get(j).getName(), GROUP_A.get(j).getSeat());
//System.out.printf(",");
}
} System.out.println();
}
}
public void BusBoundC() {
int temp = 0;
for (int i = 0; i < BUSC.size(); i++) {
if (BUSC.get(i).getName().equals("C" + i)) {
temp++;
}
}
System.out.println();
System.out.printf("%s >> ==== City Bound ====", Thread.currentThread().getName());
System.out.println();
for (int i = 0; i < temp; i++) {
System.out.printf("%s >> %s : ", Thread.currentThread().getName(), "C" + i);
for (int j = 0; j < GROUP_C.size(); j++) {
if (GROUP_C.get(j).getBusname().equals("C" + i)) {
System.out.printf(" %-20s(%2d seats)", GROUP_C.get(j).getName(), GROUP_C.get(j).getSeat());
//System.out.printf(",");
}
} System.out.println();
}
}
synchronized public void allocateBus(Data d) {
TicketCounter T = (TicketCounter) (Thread.currentThread());
while (d.getSeat() != 0) {
if ("A".equals(d.getDestination())) {
if (BUSA.size() == 0 || BUSA.get(BUSA.size() - 1).getAvailableSeat() == 0) {
BUSA.add(new Bus("A" + BUSA.size()));
}
if (d.getSeat() <= BUSA.get(BUSA.size() - 1).getAvailableSeat()) {
System.out.printf("%s >> Transaction %2d : %-20s(%2d seats) bus %s\n", T.getName(), d.getTransaction(), d.getName(), d.getSeat(), BUSA.get(BUSA.size() - 1).getName());
GROUP_A.add(new Group(BUSA.get(BUSA.size() - 1).getName(), d.getName(), d.getSeat()));
BUSA.get(BUSA.size() - 1).Bookingseat(d.getSeat());
d.finishedBooking(d.getSeat());
} else {
System.out.printf("%s >> Transaction %2d : %-20s(%2d seats) bus %s\n", T.getName(), d.getTransaction(), d.getName(), BUSA.get(BUSA.size() - 1).getAvailableSeat(), BUSA.get(BUSA.size() - 1).getName());
GROUP_A.add(new Group(BUSA.get(BUSA.size() - 1).getName(), d.getName(), BUSA.get(BUSA.size() - 1).getAvailableSeat()));
d.finishedBooking(BUSA.get(BUSA.size() - 1).getAvailableSeat());
BUSA.get(BUSA.size() - 1).Bookingseat(BUSA.get(BUSA.size() - 1).getAvailableSeat());
}
} else {
if (BUSC.size() == 0 || BUSC.get(BUSC.size() - 1).getAvailableSeat() == 0) {
BUSC.add(new Bus("C" + BUSC.size()));
}
if (d.getSeat() <= BUSC.get(BUSC.size() - 1).getAvailableSeat()) {
System.out.printf("%s >> Transaction %2d : %-20s(%2d seats) bus %s\n", T.getName(), d.getTransaction(), d.getName(), d.getSeat(), BUSC.get(BUSC.size() - 1).getName());
GROUP_C.add(new Group(BUSC.get(BUSC.size() - 1).getName(), d.getName(), d.getSeat()));
BUSC.get(BUSC.size() - 1).Bookingseat(d.getSeat());
d.finishedBooking(d.getSeat());
} else {
System.out.printf("%s >> Transaction %2d : %-20s(%2d seats) bus %s\n", T.getName(), d.getTransaction(), d.getName(), BUSC.get(BUSC.size() - 1).getAvailableSeat(), BUSC.get(BUSC.size() - 1).getName());
GROUP_C.add(new Group(BUSC.get(BUSC.size() - 1).getName(), d.getName(), BUSC.get(BUSC.size() - 1).getAvailableSeat()));
d.finishedBooking(BUSC.get(BUSC.size() - 1).getAvailableSeat());
BUSC.get(BUSC.size() - 1).Bookingseat(BUSC.get(BUSC.size() - 1).getAvailableSeat());
}
}
}
}
}
class Group {
private String busname, name;
private int seat;
public Group(String n, String b, int s) {
busname = n;
name = b;
seat = s;
}
public String getName() { return name; }
public String getBusname() { return busname; }
public int getSeat() { return seat; }
}
class Bus {
private String Busname, group_name;
private int availableseat, seat;
public int getAvailableSeat() { return availableseat; }
public String getName() { return Busname; }
public void Bookingseat(int s) { availableseat -= s; }
public String getGroupname() { return group_name; }
public Bus(String n) {
availableseat = BusLine.max_seat;
Busname = n;
}
public Bus(String n, int s) {
group_name = n;
seat = s;
}
public Bus(String n, String gn, int s) {
Busname = n;
group_name = gn;
availableseat = s;
}
}
class Data {
private String name, destination;
private int seat, transaction, count = 0;
public int getCount() { return count; }
public int getTransaction() { return transaction; }
public String getName() { return name; }
public int getSeat() { return seat; }
public String getDestination() { return destination; }
public void finishedBooking(int s) { seat -= s; }
public Data(int t, String n, int s, String d) {
transaction = t;
name = n;
seat = s;
destination = d;
}
}
class TicketCounter extends Thread {
ArrayList<Data> transaction;
BusLine Airport, City;
private CyclicBarrier cfinish;
public void setCyclicBarrier(CyclicBarrier f) {
cfinish = f;
}
public TicketCounter(String n, ArrayList<Data> d, BusLine a, BusLine c) {
super(n);
transaction = d;
Airport = a;
City = c;
}
public void run() {
for (int i = 0; i < transaction.size(); i++) {
if (transaction.get(i).getTransaction() == BusLine.checkpoint) {
try {
cfinish.await();
cfinish.await();
} catch (Exception e) {}
}
if ("A".equals(transaction.get(i).getDestination())) {
Airport.allocateBus(transaction.get(i));
} else {
City.allocateBus(transaction.get(i));
}
}
}
}
class Userinput {
private ArrayList<Data> DATA1 = new ArrayList<Data>();
private ArrayList<Data> DATA2 = new ArrayList<Data>();
private ArrayList<Data> DATA3 = new ArrayList<Data>();
public Userinput() {}
public ArrayList<Data> getDATA1() { return DATA1; }
public ArrayList<Data> getDATA2() { return DATA2; }
public ArrayList<Data> getDATA3() { return DATA3; }
public void input() {
String infile[] = {"T1.txt", "T2.txt", "T3.txt"};
for (int i = 0; i < 3; i++) {
boolean opensuccess = false;
while (!opensuccess) {
try ( Scanner scanfile = new Scanner(new File(infile[i]));) {
while (scanfile.hasNext()) {
opensuccess = true;
String line = scanfile.nextLine();
String[] buf = line.split(",");
int transaction = Integer.parseInt(buf[0].trim());
String name = buf[1].trim();
int seat = Integer.parseInt(buf[2].trim());
String destination = buf[3].trim();
Data d = new Data(transaction, name, seat, destination);
switch (i) {
case 0: DATA1.add(d);
break;
case 1: DATA2.add(d);
break;
case 2: DATA3.add(d);
break;
}
}
} catch (FileNotFoundException e) {
System.out.println(e);
Scanner scan = new Scanner(System.in);
System.out.println("Enter new file name : ");
infile[i] = scan.nextLine();
}
}
}
}
}
public class Simulation {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Thread Th = Thread.currentThread();
System.out.printf("%s >> Enter max seats = ", Th.getName());
System.out.println();
int max_seat = scan.nextInt();
System.out.printf("%s >> Enter checkpoints = ", Th.getName());
System.out.println();
int checkpoint = scan.nextInt();
Userinput U = new Userinput();
BusLine Airport = new BusLine(max_seat, checkpoint, "A");
BusLine City = new BusLine(max_seat, checkpoint, "C");
CyclicBarrier CB = new CyclicBarrier(4);
U.input();
TicketCounter[] T = {
new TicketCounter("T1", U.getDATA1(), Airport, City),
new TicketCounter("T2", U.getDATA2(), Airport, City),
new TicketCounter("T3", U.getDATA3(), Airport, City)};
for (int i = 0; i < 3; i++) {
T[i].setCyclicBarrier(CB);
T[i].start();
}
try {
CB.await();
Airport.printAirportCheckpoint();
City.printCityCheckpoint();
CB.await();
}catch (Exception e){}
for (int i = 0; i < 3; i++) {
try {
T[i].join();
} catch (Exception e) {
System.err.println(e);
}
}
Airport.BusBoundA();
City.BusBoundC();
}
}
Related
I have an arraylist of object type:
public static ArrayList crimes = new ArrayList();
The CityCrime.java has the following:
public class CityCrime {
//Instance variables
private String city;
private String state;
private int population;
private int murder;
private int robbery;
private int assault;
private int burglary;
private int larceny;
private int motorTheft;
public int totalCrimes;
public static void main(String[] args) {
}
public int getTotalCrimes() {
return totalCrimes;
}
public void setTotalCrimes(int murder, int robbery, int assault, int burglary, int larceny, int motorTheft) {
this.totalCrimes = murder + robbery + assault + burglary + larceny + motorTheft;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
if(state.equalsIgnoreCase("ALABAMA")) {
this.state = "AL";
}
else if(state.equalsIgnoreCase("ALASKA")) {
this.state = "AK";
}
else if(state.equalsIgnoreCase("ARIZONA")) {
this.state = "AR";
}
//etc
}
public int getPopulation() {
return population;
}
public void setPopulation(int population) {
this.population = population;
}
public int getMurder() {
return murder;
}
public void setMurder(int murder) {
this.murder = murder;
}
public int getRobbery() {
return robbery;
}
public void setRobbery(int robbery) {
this.robbery = robbery;
}
public int getAssault() {
return assault;
}
public void setAssault(int assault) {
this.assault = assault;
}
public int getBurglary() {
return burglary;
}
public void setBurglary(int burglary) {
this.burglary = burglary;
}
public int getLarceny() {
return larceny;
}
public void setLarceny(int larceny) {
this.larceny = larceny;
}
public int getMotorTheft() {
return motorTheft;
}
public void setMotorTheft(int motorTheft) {
this.motorTheft = motorTheft;
}
public static void showAllMurderDetails() {
for (CityCrime crime : StartApp.crimes) {
System.out.println("Crime: City= " + crime.getCity() + ", Murder= " + crime.getMurder());
}
System.out.println();
}
public static int showAllViolentCrimes() {
int total = 0;
for(CityCrime crime : StartApp.crimes) {
total=total+crime.getMurder();
total=total+crime.getRobbery();
total=total+crime.getAssault();
}
System.out.println("Total of violent crimes: " + total);
return total;
}
public static int getPossessionCrimes() {
int total=0;
for (CityCrime crime : StartApp.crimes) {
total = total + crime.getBurglary();
total = total + crime.getLarceny();
total = total + crime.getMotorTheft();
}
System.out.println("Total of possession crimes: " + total);
return total;
}
}
The CityCrime ArrayList gets popular from another csv file:
public static void readCrimeData() {
File file = new File("crimeUSA.csv");
FileReader fileReader;
BufferedReader bufferedReader;
String crimeInfo;
String[] stats;
try {
fileReader = new FileReader(file);
bufferedReader = new BufferedReader(fileReader);
crimeInfo = bufferedReader.readLine();
crimeInfo = bufferedReader.readLine();
do {
CityCrime crime = new CityCrime(); // Default constructor
stats = crimeInfo.split(",");
{
if (stats[0] != null) {
crime.setCity(stats[0]);
}
if (stats[1] != null) {
crime.setState(stats[1]);
}
if (stats[2] != null) {
if (Integer.parseInt(stats[2]) >= 0) {
crime.setPopulation(Integer.parseInt(stats[2]));
}
}
if (stats[3] != null) {
if (Integer.parseInt(stats[3]) >= 0) {
crime.setMurder(Integer.parseInt(stats[3]));
}
}
if (stats[4] != null) {
if (Integer.parseInt(stats[4]) >= 0) {
crime.setRobbery(Integer.parseInt(stats[4]));
}
}
if (stats[5] != null) {
if (Integer.parseInt(stats[5]) >= 0) {
crime.setAssault(Integer.parseInt(stats[5]));
}
}
if (stats[6] != null) {
if (Integer.parseInt(stats[6]) >= 0) {
crime.setBurglary(Integer.parseInt(stats[6]));
}
}
if (stats[7] != null) {
if (Integer.parseInt(stats[7]) >= 0) {
crime.setLarceny(Integer.parseInt(stats[7]));
}
}
if (stats[8] != null) {
if (Integer.parseInt(stats[8]) >= 0) {
crime.setMotorTheft(Integer.parseInt(stats[8]));
}
}
crime.setTotalCrimes(Integer.parseInt(stats[3]), Integer.parseInt(stats[4]), Integer.parseInt(stats[5]), Integer.parseInt(stats[6]), Integer.parseInt(stats[7]), Integer.parseInt(stats[8]));
}
crimes.add(crime);
System.out.println(crime);
crimeInfo = bufferedReader.readLine();
} while (crimeInfo != null);
fileReader.close();
bufferedReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
I want to sort the array list and output to the csv file the list of robberies in descending order with the corresponding city. So far I have got the following, but I am stuck and not sure if going in the right direction. I'm relatively new to Java as you can probably tell so would appreciate it in as simple terms as can be:
public static void writeToFile() throws IOException {
File csvFile = new File("Robbery.csv");
FileWriter fileWriter = new FileWriter(csvFile);
ArrayList<Integer> robberyRates = new ArrayList();
for(CityCrime crime : crimes) {
robberyRates.add(crime.getRobbery());
}
Collections.sort(robberyRates);
}
The desired output will be for example:
Robbery,City
23511,New York
15863,Chicago
14353,Los Angeles
11371,Houston
10971,Philadelphia
etc…
Your help is appreciated. I have searched any page I can find on Google, but all I see from other example is writing to the csv from a set String ArrayList where they know the number of lines etc. Thankyou
You can try something like this:
public static void writeToFile() throws IOException {
File csvFile = new File("Robbery.csv");
try(FileWriter fileWriter = new FileWriter(csvFile)) { // try-with-resources to be sure that fileWriter will be closed at end
StringBuilder stringBuilder = new StringBuilder(); // Betther than String for multiple concatenation
crimes.sort(Comparator.comparingInt(CityCrime::getRobbery).reversed()); // I want to compare according to getRobbery, as Int, in reversed order
stringBuilder.append("Robbery")
.append(',')
.append("City")
.append(System.lineSeparator()); // To get new line character according to OS
for (final var crime : crimes)
stringBuilder.append(crime.getRobbery())
.append(',')
.append(crime.getCity())
.append(System.lineSeparator());
fileWriter.write(stringBuilder.toString());
}
}
If you are stuck because you can't figure out how to write a list, convert your list into a String and print the String instead.
I commented the piece of code, if you have any questions, don't hesitate.
Another solution is to use specific CSV parser library, OpenCSV for example.
It makes it easier to read and write CSV file.
Here a tutorial about OpenCSV:
https://mkyong.com/java/how-to-read-and-parse-csv-file-in-java/
I do not usually ask here.
I have a problem with the code I wrote down - I built a compression code - implementation of LZ77.
Everything works in code - when I use files that are based on ascii text in English.
When I use a bmp file - which works differently from a plain text file - I have a problem.
In a text file - I can write the character as it is - it works.
In the bmp file - when I try to compress it - I come across characters that are not English text letters - so I can not compress the file
That I'm trying to write a letter in English into a String builder it works - but in other characters - I can not write them inside the stringBuilder - as I try to write them - it performs null.
code:
main:
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException, ClassNotFoundException
{
String inPath = "C:\\Users\\avraam\\Documents\\final-assignment\\LZ77\\Tiny24bit.bmp";
String outPath = "C:\\Users\\avraam\\Documents\\final-assignment\\LZ77\\encoded.txt";
String decompressedPath = "C:\\Users\\avraam\\Documents\\final-assignment\\LZ77\\decoded.bmp";
int windowSize = 512;
int lookaheadBufferSize = 200;
LZ77 compress = new LZ77(inPath,outPath,windowSize,lookaheadBufferSize);
compress.compress();
LZ77 decompress = new LZ77(outPath,decompressedPath,windowSize,lookaheadBufferSize);
decompress.decompress();
System.out.println("DONE!");
}
}
LZ77
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Writer;
import java.nio.file.Files;
import java.util.BitSet;
public class LZ77 {
private String inPath = null;
private String outPath = null;
private File inFile;
private File outFile;
private final int windowSize;
private final int lookaheadBufferSize;
private final int searchBufferSize;
private int nextByteIndex = 0;
private int nextBitIndex = 0;
private int currentSearchBufferSize = 0;
private int currentLookaheadBufferSize = 0;
private int appendToWindowBuffer = 0;
private byte[] source = null;
public LZ77(String inPath,String outPath,int windowSize,int lookaheadBufferSize) throws IOException
{
this.inPath = inPath;
this.outPath = outPath;
this.inFile = new File(inPath);
this.outFile = new File(outPath);
this.windowSize = windowSize;
this.lookaheadBufferSize = lookaheadBufferSize;
this.searchBufferSize = windowSize - lookaheadBufferSize;
this.source = Files.readAllBytes(inFile.toPath());
}
public void compress() throws IOException
{
StringBuilder dictionary = new StringBuilder();
bufferInitialize(dictionary);
StringBuilder compressed = new StringBuilder();
encode(dictionary,compressed);
addSizeBitsMod64(compressed);
//System.out.println(compressed);
writeFile(compressed);
}
public void bufferInitialize(StringBuilder dictionary)
{
for (int i = 0; i < lookaheadBufferSize; i++) {
if(source.length>nextByteIndex) {
dictionary.append((char)Byte.toUnsignedInt(source[nextByteIndex]));
nextByteIndex++;
currentLookaheadBufferSize++;
}
else
{
break;
}
}
}
public void encode(StringBuilder dictionary,StringBuilder compressed)
{
while(currentLookaheadBufferSize > 0)
{
Match match = findMatch(dictionary);
WriteMatch(compressed,match.offset,match.length,dictionary.charAt(currentSearchBufferSize + match.length));
appendToWindowBuffer = increaseBuffer(match.length);
appendBuffer(dictionary);
}
}
public Match findMatch(StringBuilder dictionary)
{
Match match= new Match(0,0, "");
String matchedString = null;
int offset;
int matchLookAheadIndex = currentSearchBufferSize;
if(!haveAnyMatch(dictionary))
{
}
else {
matchedString = "" + dictionary.charAt(matchLookAheadIndex);
offset = findMatchIndex(dictionary,matchedString);
while(offset != -1 && matchLookAheadIndex < dictionary.length() - 1)
{
match.SetLength(match.length + 1);
match.SetOffset(offset);
match.SetValue(matchedString);
matchLookAheadIndex++;
matchedString +=dictionary.charAt(matchLookAheadIndex);
offset = findMatchIndex(dictionary,matchedString);
}
}
return match;
}
public int findMatchIndex(StringBuilder dictionary,String value)
{
int stringLength = value.length();
String tmpMatch = null;
int offsetMatch;
for (int i = currentSearchBufferSize - 1; i >=0; i--)
{
tmpMatch = dictionary.substring(i, i +stringLength );
offsetMatch = currentSearchBufferSize - i;
if(tmpMatch.equals(value))
{
return offsetMatch;
}
}
return -1;
}
public boolean haveAnyMatch(StringBuilder dictionary)
{
if (currentSearchBufferSize == 0)
{
return false;
}
if(!isExistInSearchBuffer(dictionary,dictionary.charAt(currentSearchBufferSize)))
{
return false;
}
return true;
}
public boolean isExistInSearchBuffer(StringBuilder dictionary, char isCharAtDictionary)
{
for (int i = 0; i < currentSearchBufferSize; i++) {
if(dictionary.charAt(i) == isCharAtDictionary)
{
return true;
}
}
return false;
}
public int increaseBuffer(int matchLength)
{
return 1 + matchLength;
}
public int findBitSize(int decimalNumber) {
if(decimalNumber >= 256)
{
return 16;
}
else
{
return 8;
}
}
public void convertStringToBitSet(StringBuilder compressed,BitSet encodedBits)
{
for (int i = 0; i < compressed.length(); i++) {
if(compressed.charAt(i)==1)
{
encodedBits.set(i);
}
}
}
public BitSet ConvertToBits(StringBuilder compressed)
{
BitSet encodedBits = new BitSet(compressed.length());
int nextIndexOfOne = compressed.indexOf("1", 0);
while( nextIndexOfOne != -1)
{
encodedBits.set(nextIndexOfOne);
nextIndexOfOne++;
nextIndexOfOne = compressed.indexOf("1", nextIndexOfOne);
}
return encodedBits;
}
public void writeFile(StringBuilder compressed) throws IOException
{
BitSet encodedBits = new BitSet(compressed.length());
encodedBits = ConvertToBits(compressed);
FileOutputStream writer = new FileOutputStream(this.outPath);
ObjectOutputStream objectWriter = new ObjectOutputStream(writer);
objectWriter.writeObject(encodedBits);
objectWriter.close();
}
public void appendBuffer(StringBuilder dictionary)
{
for (int i = 0; i < appendToWindowBuffer && i < source.length; i++) {
if(ableDeleteChar(dictionary))
{
dictionary.deleteCharAt(0);
}
if(nextByteIndex<source.length)
{
char nextByte = (char)Byte.toUnsignedInt(source[nextByteIndex]);
dictionary.append(nextByte);
nextByteIndex++;
}
else
{
currentLookaheadBufferSize--;
}
if(currentSearchBufferSize < searchBufferSize)
{
currentSearchBufferSize++;
}
}
appendToWindowBuffer = 0;
}
public void WriteMatch(StringBuilder compressed,int offset, int length, char character)
{
/*int offsetBitSizeCheck, lengthBitSizeCheck;
offsetBitSizeCheck = findBitSize(offset);
lengthBitSizeCheck = findBitSize(length);
*/
String offsetInBits = writeInt(offset);
String LengthInBits = writeInt(length);
String characterInBits = writeChar(character);
String totalBits = offsetInBits + LengthInBits + characterInBits;
compressed.append(totalBits);
//compressed.append("<"+ offset + ","+ length +","+ character + ">");
System.out.print("<"+ offset + ","+ length +","+ character + ">");
}
public String writeInt(int decimalNumber)
{
int BitSizeCheck = findBitSize(decimalNumber);
StringBuilder binaryString = new StringBuilder();
binaryString.append(convertNumToBinaryString(decimalNumber));
while (binaryString.length() < BitSizeCheck)
{
binaryString.insert(0, "0");
}
if(BitSizeCheck == 8)
{
binaryString.insert(0, "0");
}
else
{
binaryString.insert(0, "1");
}
return binaryString.toString();
}
public String convertNumToBinaryString(int decimalNumber)
{
return Integer.toString(decimalNumber, 2);
}
public String writeChar(char character)
{
StringBuilder binaryString = new StringBuilder();
binaryString.append(convertNumToBinaryString((int)character));
while (binaryString.length() < 8)
{
binaryString.insert(0, "0");
}
return binaryString.toString();
}
public boolean ableDeleteChar(StringBuilder dictionary)
{
if(dictionary.length() == windowSize )
{
return true;
}
if(currentLookaheadBufferSize < lookaheadBufferSize)
{
if(currentSearchBufferSize == searchBufferSize)
{
return true;
}
}
return false;
}
public void addSizeBitsMod64(StringBuilder compressed)
{
int bitsLeft = compressed.length()%64;
String bitsLeftBinary = writeInt(bitsLeft);
compressed.insert(0, bitsLeftBinary);
}
public void decompress () throws ClassNotFoundException, IOException
{
BitSet source = readObjectFile();
//System.out.println(source.toString());
StringBuilder decompress = new StringBuilder ();
int bitSetLength = findLengthBitSet(source);
decode(decompress,bitSetLength,source);
writeDecode(decompress);
}
public BitSet readObjectFile() throws IOException, ClassNotFoundException
{
FileInputStream input = new FileInputStream(this.inPath);
ObjectInputStream objectInput = new ObjectInputStream(input);
BitSet restoredDataInBits = (BitSet) objectInput.readObject();
objectInput.close();
return restoredDataInBits;
}
public void decode(StringBuilder decompress, int bitSetLength,BitSet source)
{
System.out.println("decode: ");
System.out.println();
while(nextBitIndex < bitSetLength)
{
Match match = convertBitsToMatch(source);
//System.out.print("<"+ match.offset + ","+ match.length +","+ match.value + ">");
addDecode(decompress, match);
}
}
public void addDecode(StringBuilder decompress, Match match)
{
int RelativeOffset;
char decodeChar;
if(match.length == 0 && match.offset == 0)
{
decompress.append(match.value);
}
else
{
RelativeOffset = decompress.length() - match.offset;
System.out.println(RelativeOffset);
for (int i = 0; i < match.length; i++) {
decodeChar = decompress.charAt(RelativeOffset);
decompress.append(decodeChar);
RelativeOffset++;
}
decompress.append(match.value);
}
}
public Match convertBitsToMatch(BitSet source)
{
int offset;
int length;
char character;
if(source.get(nextBitIndex) == false)
{
nextBitIndex++;
offset = findOffsetLengthMatch(8,source);
}
else
{
nextBitIndex++;
offset = findOffsetLengthMatch(16,source);
}
if(source.get(nextBitIndex) == false)
{
nextBitIndex++;
length = findOffsetLengthMatch(8,source);
}
else
{
nextBitIndex++;
length = findOffsetLengthMatch(16,source);
}
character = findCharacterMatch(source);
//System.out.println("offset: " + offset + " length: " + length);
Match match = new Match(length,offset,""+character);
System.out.print("<"+ match.offset + ","+ match.length +","+ match.value + ">");
return match;
}
public int findOffsetLengthMatch(int index, BitSet source)
{
StringBuilder offsetLengthBinary = new StringBuilder();
for (int i = 0; i < index; i++) {
if(source.get(nextBitIndex) == false)
{
offsetLengthBinary.append('0');
nextBitIndex++;
}
else
{
offsetLengthBinary.append('1');
nextBitIndex++;
}
}
int offsetLengthDecimal = convertBinaryStringToDecimal(offsetLengthBinary);
//System.out.println("problem here: " + offsetLengthDecimal + " the binary is : " + offsetLengthBinary);
return offsetLengthDecimal;
}
public char findCharacterMatch(BitSet source)
{
StringBuilder charBinary = new StringBuilder();
for (int i = 0; i < 8; i++) {
if(source.get(nextBitIndex) == false)
{
charBinary.append('0');
nextBitIndex++;
}
else
{
charBinary.append('1');
nextBitIndex++;
}
}
char charDecimal = (char)convertBinaryStringToDecimal(charBinary);
return charDecimal;
}
public int findLengthBitSet(BitSet source)
{
StringBuilder lengthBinary = new StringBuilder();
for (int i = 0; i < 9; i++) {
if(source.get(i) == false)
{
lengthBinary.append('0');
nextBitIndex++;
}
else
{
lengthBinary.append('1');
nextBitIndex++;
}
}
int lengthModule = convertBinaryStringToDecimal(lengthBinary);
int lengthNotUsed = 64 - lengthModule;
int fullLength = source.size() - lengthNotUsed + 9 ;
return fullLength;
}
public int convertBinaryStringToDecimal(StringBuilder lengthBinary)
{
int length = Integer.parseInt(lengthBinary.toString(), 2);
//System.out.println("length: " + length + "lengthBinary: " + lengthBinary);
return length;
}
public void writeDecode (StringBuilder decompress) throws IOException
{
Writer write = new FileWriter(this.outFile);
write.write(decompress.toString());
write.close();
}
}
Match
public class Match {
protected int length;
protected int offset;
protected String value;
public Match(int length, int offset, String value)
{
this.length=length;
this.offset=offset;
this.value = value;
}
public void SetOffset(int offset) { this.offset = offset; }
public void SetLength(int length) { this.length = length; }
public void SetValue(String value) { this.value = value; }
public void AddValue(char value) { this.value += value; }
public void Reset()
{
this.offset = 0;
this.length = 0;
this.value = "";
}
}
Can you please read through below code and help to let me know if i need to use synchronized keyword with the concurrent hash map in this example?
The main problem is i dont understand when a synchronized keyword needs to be used in compound operations in a concurrent hash map.can someone please help
import java.util.Map;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
class Pair {
public final Integer x;
public final Integer y;
public Pair(Integer x, Integer y) {
this.x = x;
this.y = y;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((x == null) ? 0 : x.hashCode());
result = prime * result + ((y == null) ? 0 : y.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Pair other = (Pair) obj;
if (x == null) {
if (other.x != null)
return false;
} else if (!x.equals(other.x))
return false;
if (y == null) {
if (other.y != null)
return false;
} else if (!y.equals(other.y))
return false;
return true;
}
}
class Order{
int clOrdId;
int origClOrdId;
String symbol;
int qty;
double price;
#Override
public String toString() {
return "Order [clOrdId=" + clOrdId + ", origClOrdId=" + origClOrdId + ", symbol=" + symbol + ", qty=" + qty
+ ", price=" + price + ", side=" + side + "]";
}
char side;
Order(int clOrdId,String symbol,int qty,double price,char side){
this.clOrdId=clOrdId;
this.symbol=symbol;
this.qty=qty;
this.price=price;
this.side=side;
}
Order(int clOrdId,int origClOrdId,String symbol,int qty,double price,char side){
this.clOrdId=clOrdId;
this.origClOrdId=origClOrdId;
this.symbol=symbol;
this.qty=qty;
this.price=price;
this.side=side;
}
}
class Message {
int sessionId;
Order order;
Message(int sessionId, Order order) {
this.sessionId = sessionId;
this.order = order;
}
#Override
public String toString() {
return "Message [sessionId=" + sessionId + ", order=" + order + "]";
}
}
/*
* Different clients can submit different messages 1. Each message has a
* sessionId and a string msg 2. Each of the messages on a particular session
* need to be processed sequentially
*/
public class Concurrency {
private Map<Integer, BlockingDeque<Runnable>> pendingTasks = new ConcurrentHashMap<>();
private Map<Pair,Order> orderMap = new ConcurrentHashMap<>();
private ExecutorService executorService = Executors.newFixedThreadPool(13);
public void submitMsg(final Message msg) {
submitTask(msg, () -> {
if(msg.order.origClOrdId==0){
print("Received new order msg " + msg);
sleep(1000);
}else{
Pair key = new Pair(msg.sessionId,msg.order.origClOrdId);
if(orderMap.containsKey(key)){
if(isOnlyAggressivePriceMod(msg, key) ){
print("Aggressive price modification "+ msg);
}else if(isOnlyQtyModUp(msg, key)){
print(" Quantity modification up only for "+ msg);
}else if(isOnlyQtyDown(msg, key)){
print(" Quantity modification down only for "+ msg);
}
}
}
orderMap.put(new Pair(msg.sessionId,msg.order.clOrdId), msg.order);
});
}
private boolean isOnlyQtyDown(final Message msg, Pair key) {
return msg.order.qty<orderMap.get(key).qty && Double.compare(msg.order.price,orderMap.get(key).price)==0;
}
private boolean isOnlyQtyModUp(final Message msg, Pair key) {
return msg.order.qty>orderMap.get(key).qty && Double.compare(msg.order.price,orderMap.get(key).price)==0;
}
private boolean isOnlyAggressivePriceMod(final Message msg, Pair key) {
return ((Double.compare(msg.order.price,orderMap.get(key).price)>0 && msg.order.side=='B') ||
(Double.compare(msg.order.price,orderMap.get(key).price)<0 && msg.order.side=='S')) && Double.compare(msg.order.qty,orderMap.get(key).qty)==0;
}
private void sleep(int time){
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void print(String msg){
System.out.println(msg);
}
private void submitTask(final Message msg, Runnable task) {
synchronized(pendingTasks){
if (pendingTasks.containsKey(msg.sessionId)) {
pendingTasks.get(msg.sessionId).add(task);
return;
}
}
BlockingDeque<Runnable> pendingTasksPerSession = new LinkedBlockingDeque<Runnable>();
pendingTasksPerSession.push(task);
pendingTasks.put(msg.sessionId, pendingTasksPerSession);
executorService.submit(new SynchronizedTask(msg, task));
}
public class SynchronizedTask implements Runnable {
Message msg;
Runnable task;
public SynchronizedTask(Message msg, Runnable task) {
this.msg = msg;
this.task = task;
}
public void run() {
task.run();
BlockingDeque<Runnable> pendingTasksForSession = pendingTasks.get(msg.sessionId);
if (!pendingTasksForSession.remove(task)) {
return;
}
if (!pendingTasksForSession.isEmpty())
executorService.submit(new SynchronizedTask(msg, pendingTasksForSession.getFirst()));
}
}
public static void main(String args[]) {
Concurrency c = new Concurrency();
for(int i =1;i<10;i++){
c.submitMsg(new Message(i, new Order(10,"0001.HK",2000*i,200+i,'B')));
c.submitMsg(new Message(i, new Order(11,10,"0001.HK",1000*i,200+i,'B')));
c.submitMsg(new Message(i, new Order(12,11,"0001.HK",2000*i,201+i,'B')));
}
for(int i =1;i<10;i++){
c.submitMsg(new Message(i, new Order(10,"0001.HK",2000*i,200+i,'S')));
c.submitMsg(new Message(i, new Order(11,10,"0001.HK",1000*i,200+i,'S')));
c.submitMsg(new Message(i, new Order(12,11,"0001.HK",2000*i,201+i,'S')));
}
}
}
I am expecting 5 results i.e. 1, 2, 3, 4, 5 yet I am getting far more? can someone please help me understand semaphores? surely as each thread calls the run method using "start", it should add 1
to the int aNumber and then print aNumber.
I don't understand why I get more than five results.
// mainClass creates Semaphore, so Copier class no longer needed
import java.util.concurrent.Semaphore;
public class mainClass {
public static void main(String[] args) throws InterruptedException {
Semaphore cp1 = new Semaphore(1, true);
Worker[] workers = new Worker[5];
for (int x=0;x<5;x++) {
workers[x] = new Worker("w" + x, cp1);
}
for (int x=0;x<5;x++) {
workers[x].start();
}
for (int x=0;x<5;x++) {
workers[x].join();
}
}
}
import java.util.concurrent.Semaphore;
public class Worker extends Thread{
int aNumber = 0;
String myName;
Semaphore myCopier;
public Worker(String nameIn, Semaphore copierIn) {
myName = nameIn;
myCopier = copierIn;
}
public void run() {
for (int x=0;x<5;x++) {
try {
sleep((int) (Math.random() * 5000)); // do some filing
myCopier.acquire();
aNumber +=1;
//System.out.println(myName + " doing some copying");
System.out.println(aNumber);
sleep((int) (Math.random() * 1000)); // do some copying
myCopier.release();
} catch (InterruptedException e) { }
}
}
}
I could not clearly get your intention. Are you trying to use semaphores to print the nos ( 1 to 5) in sequence by each thread? In that case, you can try the below:
//mainClass creates Semaphore, so Copier class no longer needed
import java.util.concurrent.Semaphore;
public class mainClass {
public static void main(String[] args) throws InterruptedException {
Semaphore cp1 = new Semaphore(1, true);
Worker[] workers = new Worker[5];
for (int x=0;x<5;x++) {
workers[x] = new Worker("w" + x, cp1, x+1);
}
for (int x=0;x<5;x++) {
workers[x].start();
}
for (int x=0;x<5;x++) {
workers[x].join();
}
}
}
class Worker extends Thread{
int aNumber = 0;
String myName;
Semaphore myCopier;
public Worker(String nameIn, Semaphore copierIn, int no) {
myName = nameIn;
myCopier = copierIn;
aNumber = no;
}
public void run() {
/*for (int x=0;x<5;x++) {*/
try {
//sleep((int) (Math.random() * 5000)); // do some filing
myCopier.acquire();
//System.out.println(myName + " doing some copying");
System.out.println("Name of the thread:" + myName + " Printed No is:" + aNumber);
//sleep((int) (Math.random() * 1000)); // do some copying
myCopier.release();
} catch (InterruptedException e) { }
//}
}
}
I have a program that creates a queue, enqueues objects to the queue and then dequeues them one by one if the queue is not empty. The problem I am having is that the queue comes up empty each time it is checked. Print is called on the queue after enqueuing each object and it prints the queue's contents just fine.
import java.util.*;
import java.io.*;
public class Processor2
{
private LinkedQueue queue = new LinkedQueue();
private int time = 0;
private int count = 100;
private int amount = 0;
private PrintWriter out;
private Person temp;
private boolean var;
private Random randomNum = new Random();;
private String turn;
private int popCount=0;
private int loopCount =0;
public void start()
{
amount = randomNum.nextInt(5);
amount += 5;
pop(amount, time);
sim();
}
public void pop(int num, int time)
{
for(int i=1; i<=num; i++)
{
Person pe = new Person(i, time, 0);
queue.enqueue(pe);
System.out.println(queue);
}
popCount += num;
}
public void sim()
{
try
{
out = new PrintWriter(new FileWriter("output.txt"));
while(loopCount<=100)
{
var = queue.isEmpty();
if(var=true)
{
System.out.println("queue is empty");
}
if(var=false)
{
Object temp = queue.dequeue();
double rand = Math.random();
if(rand < 0.5)
{
System.out.println("inside if else statement");
// does stuff with object //
loopCount++;
}
else
{
System.out.println("inside if else statement");
// does stuff with object //
loopCount++;
}
}
}
out.close();
}
catch (IOException ioe)
{
System.out.println("Error Writing to File: " + ioe);
}
}
}
there doesn't seem to be anything wrong with the queue's isEmpty() method, but here it is:
public boolean isEmpty()
{
if(count == 0)
{
return true;
}
else
{
return false;
}
}
var = queue.isEmpty();
if(var=true) // this line *sets* var to true
{
System.out.println("queue is empty");
}
If you change if (var=true) to if(var==true) or just if(var) you should see a different result