CyclicBarrier is a very interesting functionality for Concurrency in Java. Here is a quick example which shows how this is implemented
1. Imagine a scenario where two doctors are needed to see a patient. One doctor has to wait while the other gets available.
2. So a doctor waits at a "Barrier" for the second doctor to come and only then do both proceed with the patient
3. And this need to be Cyclic in nature for all the patients in the hospital, i.e the Barrier needs to be Cyclic in nature
4. This is a simple example which showcases the "Cyclic" nature of the CyclicBarrier. For a detailed demo, you can refer to this page
Output
Doctor Thread-1 : READY to see the Patient -BatMan
Doctor Thread-2 : READY to see the Patient -BatMan
Doctor Thread-2 : WORKING on Patient-BatMan since the team is here
Doctor Thread-1 : WORKING on Patient-BatMan since the team is here
Doctor Thread-2 : DONE with the Patient -BatMan
Doctor Thread-2 : READY to see the Patient -SuperMan
Doctor Thread-1 : DONE with the Patient -BatMan
Doctor Thread-1 : READY to see the Patient -SuperMan
Doctor Thread-1 : WORKING on Patient-SuperMan since the team is here
Doctor Thread-2 : WORKING on Patient-SuperMan since the team is here
Doctor Thread-2 : DONE with the Patient -SuperMan
Doctor Thread-2 : READY to see the Patient -IronMan
Doctor Thread-1 : DONE with the Patient -SuperMan
Doctor Thread-1 : READY to see the Patient -IronMan
Doctor Thread-1 : WORKING on Patient-IronMan since the team is here
Doctor Thread-2 : WORKING on Patient-IronMan since the team is here
Doctor Thread-1 : DONE with the Patient -IronMan
Doctor Thread-2 : DONE with the Patient -IronMan
Java Decrypted
Some pearls i found while exploring the sea of Java.
Monday, March 14, 2016
Friday, March 11, 2016
CountDownLatch Example
Lets take a situation where one thread has to wait for a few other threads to complete before it can start functioning. A few such practical scenarios could be:
1. A file can only be processed by "Thread C" once it has been read by "Thread A" and cleaned by "Thread B"
2. Data from different sources need to be combined. Multiple threads are bringing in data. The final thread has to wait until all have brought in data; only then can it combine them
To achieve this one simple way could be:
1. To make the final thread "Thread.Join" the previous thread. So the final will work only when the previous has completed. But as you can see, this will not suit sooooo many scenarios one being if there are multiple previous threads.
2. Use a complicated code based on Concurrent.Collections framework. For example we can use SynchronousQueues for implementing a simple sequential Hand over of data for the other thread to work. But again what if there are multiple non sequential threads.
CountdownLatch simplifies this
1. We create a CountDownLatch with a variable telling how many threads will be be running before the final thread can start
2. CountDown() : All other threads call this once they have completed their tasks
3. await() : The final thread calls this and waits until all the other threads have called CountDown() on the latch. Once the Countdown is done by all threads, the final thread can start working
The example i am using below is a simple example based on the wait a father has to do while his baby is being delivered. :)
Doctor Delivers, Nurse Checks, Pediatrician checks and only then can the father hold the baby. So the Father has to wait while the baby is delivered and checked by the nurse and the Pediatrician. I am keeping this simple and not ensuring the sequential handover of the baby.
The code below is self explanatory
The output is:
Nurse : Watching Delivery and Nursing the Baby....
Doctor : Delivering Baby....
Peditritian : Looking after the Baby during Delivery. Slapping and S%^T
Nurse : Baby is Fine and Beautiful.
Peditritian : Done. Phew.
Doctor : Delivered the Baby.
Father : Finally I can hold the baby.
1. A file can only be processed by "Thread C" once it has been read by "Thread A" and cleaned by "Thread B"
2. Data from different sources need to be combined. Multiple threads are bringing in data. The final thread has to wait until all have brought in data; only then can it combine them
To achieve this one simple way could be:
1. To make the final thread "Thread.Join" the previous thread. So the final will work only when the previous has completed. But as you can see, this will not suit sooooo many scenarios one being if there are multiple previous threads.
2. Use a complicated code based on Concurrent.Collections framework. For example we can use SynchronousQueues for implementing a simple sequential Hand over of data for the other thread to work. But again what if there are multiple non sequential threads.
CountdownLatch simplifies this
1. We create a CountDownLatch with a variable telling how many threads will be be running before the final thread can start
2. CountDown() : All other threads call this once they have completed their tasks
3. await() : The final thread calls this and waits until all the other threads have called CountDown() on the latch. Once the Countdown is done by all threads, the final thread can start working
The example i am using below is a simple example based on the wait a father has to do while his baby is being delivered. :)
Doctor Delivers, Nurse Checks, Pediatrician checks and only then can the father hold the baby. So the Father has to wait while the baby is delivered and checked by the nurse and the Pediatrician. I am keeping this simple and not ensuring the sequential handover of the baby.
The code below is self explanatory
The output is:
Nurse : Watching Delivery and Nursing the Baby....
Doctor : Delivering Baby....
Peditritian : Looking after the Baby during Delivery. Slapping and S%^T
Nurse : Baby is Fine and Beautiful.
Peditritian : Done. Phew.
Doctor : Delivered the Baby.
Father : Finally I can hold the baby.
Wednesday, January 20, 2016
It's been really long since I updated the blog. Will try to be more active now and include not only Java but also my thoughts on project management.
The aim of this blog was always to provide ready made code along with quick explanation on the topic. Will follow the same pattern going ahead. Cheerio!!
The aim of this blog was always to provide ready made code along with quick explanation on the topic. Will follow the same pattern going ahead. Cheerio!!
Monday, October 17, 2011
Example of Deadlock in Threads
Often we hear of Deadlocks. I tried replicating it using a simple example through threads.
Lets take an example of two people Jack and Jill; trying to exchange business cards.
Rules of exchanging cards
- You offer your business card to someone.
- The other person accepts your card and gives you his card.
DeadLock
What if both people offer each other cards at the same time? Since both have to follow the rules of exchanging cards, both of them will be stuck in a deadlock since both will wait for the other to accept their cards. (Ignore the case where they offer the card with one hand and accept it with other. Assume that both are one handed)
Java Code to Replicate the Above :
Output
Jack : I am giving card to Jill
Jill : I am giving card to Jack
Output if we uncomment the Thread.sleep try block in the code above
Jack : I am giving card to Jill
Thankyou for your card.Please Accept My Card. My Name is :Jill
Jill : I am giving card to Jack
Thankyou for your card.Please Accept My Card. My Name is :Jack
Thursday, June 23, 2011
JDBC for SQL Server
A quick copy paste code for connecting with SQL Server and executing a select statement or a Stored Procedure.
1. Imports :
2. Code :
try
{
DriverManager.registerDriver (new com.microsoft.sqlserver.jdbc.SQLServerDriver());
Connection conespacxo = null;
String connectionUrl = new String();
ConnectionUrl="jdbc:sqlserver://?.?.?.?:1433;databaseName=??;user=prabhjot;password=lamba;";
conespacxo = DriverManager.getConnection(connectionUrl);
conespacxo.setAutoCommit(false);
/*
// Executing a select statement
String selectString = "select distinct name from StudentDatabase";
Statement stmt = conespacxo.createStatement();
ResultSet rs1 = stmt.executeQuery(selectString);
while (rs1.next())
{
String prodName = rs1.getString("name");
System.out.println(prodName);
}
rs1.close();
stmt.close();
conespacxo.close();
*/
// Executing a Stored Procedure
CallableStatement call_stmt = conespacxo.prepareCall("{ call myStoredProcedure (?,?,?,?) }");
call_stmt.setString(1, "2011-06-01"); // From Date
call_stmt.setString(2, "2011-06-20"); // To Date
call_stmt.setString(3, "SharePrice"); // What to Get
call_stmt.setString(4, "Google"); // Company Name
ResultSet rs = call_stmt.executeQuery();
while (rs.next())
{
String date = rs.getString(1);
String value = rs.getString(2);
System.out.println("Generated Date: " + date);
System.out.println("Generated Value: " + value);
}
rs.close();
call_stmt.close();
conespacxo.close();
}
catch(Exception e)
{
e.printStackTrace();
}
1. Imports :
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
You will need sqljdbc4.jar in your classpath.
2. Code :
try
{
DriverManager.registerDriver (new com.microsoft.sqlserver.jdbc.SQLServerDriver());
Connection conespacxo = null;
String connectionUrl = new String();
ConnectionUrl="jdbc:sqlserver://?.?.?.?:1433;databaseName=??;user=prabhjot;password=lamba;";
conespacxo = DriverManager.getConnection(connectionUrl);
conespacxo.setAutoCommit(false);
/*
// Executing a select statement
String selectString = "select distinct name from StudentDatabase";
Statement stmt = conespacxo.createStatement();
ResultSet rs1 = stmt.executeQuery(selectString);
while (rs1.next())
{
String prodName = rs1.getString("name");
System.out.println(prodName);
}
rs1.close();
stmt.close();
conespacxo.close();
*/
// Executing a Stored Procedure
CallableStatement call_stmt = conespacxo.prepareCall("{ call myStoredProcedure (?,?,?,?) }");
call_stmt.setString(1, "2011-06-01"); // From Date
call_stmt.setString(2, "2011-06-20"); // To Date
call_stmt.setString(3, "SharePrice"); // What to Get
call_stmt.setString(4, "Google"); // Company Name
ResultSet rs = call_stmt.executeQuery();
while (rs.next())
{
String date = rs.getString(1);
String value = rs.getString(2);
System.out.println("Generated Date: " + date);
System.out.println("Generated Value: " + value);
}
rs.close();
call_stmt.close();
conespacxo.close();
}
catch(Exception e)
{
e.printStackTrace();
}
Tuesday, January 5, 2010
Manipulating Excel Through Java
Manipulation of Excel files using Java can be done by using the Jakartha POI libraries. A lot of info about this can be found on net but here is a quick and correct code for solving a few of the issues which you may encounter..
HSSFWorkbook wb = new HSSFWorkbook("Prabhjot XL File.xls");
HSSFSheet sheet = wb.getSheetAt(sheetNumber);
HSSFCellStyle style = wb.createCellStyle();
row = sheet.createRow(0); //Creating First Row
cell = row.createCell(0); //Creating First Cell
//Changing Font :
HSSFFont font = wb.createFont();
font.setFontHeightInPoints((short)8);
font.setFontName("Arial");
style.setFont(font);
//Changing Border Color and Style :
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBottomBorderColor(IndexedColors.BLUE.getIndex());
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setLeftBorderColor(IndexedColors.BLUE.getIndex());
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setRightBorderColor(IndexedColors.BLUE.getIndex());
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setTopBorderColor(IndexedColors.BLUE.getIndex());
//Changing Cell color
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setFillForegroundColor(HSSFColor.LIGHT_ORANGE.index); // Explained in detail below.
cell.setCellStyle(style); //Setting Cell Style.
cell.setCellValue("Hi"); //Setting Cell Value.
//Adding Validation For Cell values from 0-9999 only
DVConstraint dvConstraint = DVConstraint.createNumericConstraint(DVConstraint.ValidationType.INTEGER,DVConstraint.OperatorType.BETWEEN, "0", "9999");
HSSFDataValidation dataValidation;
CellRangeAddressList addressList;
addressList = new CellRangeAddressList(startRow, endRow, startCell, endCell);
dataValidation = new HSSFDataValidation(addressList, dvConstraint);
dataValidation.setErrorStyle(HSSFDataValidation.ErrorStyle.STOP);
dataValidation.createErrorBox("Invalid Input", "This cell can contain only whole numbers between 0-9999.");
sheet.addValidationData(dataValidation);
//Adding Conditional Formatting To The Cell. Format when cell's value is not equal to 0.
HSSFSheetConditionalFormatting sheetCF=sheet.getSheetConditionalFormatting();
HSSFConditionalFormattingRule rule = sheetCF.createConditionalFormattingRule(ComparisonOperator.NOT_EQUAL, "0",null );
rule.createPatternFormatting().setFillBackgroundColor(HSSFColor.LIGHT_ORANGE.index); // Create pattern with Orange background
CellRangeAddress[] cra = {new CellRangeAddress(startRow, endRow, startCell, endCell) }; // Define a region containing this cell
sheetCF.addConditionalFormatting(cra, rule); // Apply Conditional Formatting rule defined above to the regions
The issue with changing cell color is that Excel does not support all the colors which we usually pick through a color picker. To change the cell color through POI we need to pass a "short" data type value to the "style.setFillForegroundColor()" function. But who knows what value belongs to which color? I mean, can you guess which of CORNFLOWER_BLUE or LIGHT_CORNFLOWER_BLUE or LIGHT_BLUE or AQUA will look good on the cell? So here is the list of the values and the colors they resemble.
HSSFWorkbook wb = new HSSFWorkbook("Prabhjot XL File.xls");
HSSFSheet sheet = wb.getSheetAt(sheetNumber);
HSSFCellStyle style = wb.createCellStyle();
row = sheet.createRow(0); //Creating First Row
cell = row.createCell(0); //Creating First Cell
//Changing Font :
HSSFFont font = wb.createFont();
font.setFontHeightInPoints((short)8);
font.setFontName("Arial");
style.setFont(font);
//Changing Border Color and Style :
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBottomBorderColor(IndexedColors.BLUE.getIndex());
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setLeftBorderColor(IndexedColors.BLUE.getIndex());
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setRightBorderColor(IndexedColors.BLUE.getIndex());
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setTopBorderColor(IndexedColors.BLUE.getIndex());
//Changing Cell color
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setFillForegroundColor(HSSFColor.LIGHT_ORANGE.index); // Explained in detail below.
cell.setCellStyle(style); //Setting Cell Style.
cell.setCellValue("Hi"); //Setting Cell Value.
//Adding Validation For Cell values from 0-9999 only
DVConstraint dvConstraint = DVConstraint.createNumericConstraint(DVConstraint.ValidationType.INTEGER,DVConstraint.OperatorType.BETWEEN, "0", "9999");
HSSFDataValidation dataValidation;
CellRangeAddressList addressList;
addressList = new CellRangeAddressList(startRow, endRow, startCell, endCell);
dataValidation = new HSSFDataValidation(addressList, dvConstraint);
dataValidation.setErrorStyle(HSSFDataValidation.ErrorStyle.STOP);
dataValidation.createErrorBox("Invalid Input", "This cell can contain only whole numbers between 0-9999.");
sheet.addValidationData(dataValidation);
//Adding Conditional Formatting To The Cell. Format when cell's value is not equal to 0.
HSSFSheetConditionalFormatting sheetCF=sheet.getSheetConditionalFormatting();
HSSFConditionalFormattingRule rule = sheetCF.createConditionalFormattingRule(ComparisonOperator.NOT_EQUAL, "0",null );
rule.createPatternFormatting().setFillBackgroundColor(HSSFColor.LIGHT_ORANGE.index); // Create pattern with Orange background
CellRangeAddress[] cra = {new CellRangeAddress(startRow, endRow, startCell, endCell) }; // Define a region containing this cell
sheetCF.addConditionalFormatting(cra, rule); // Apply Conditional Formatting rule defined above to the regions
The issue with changing cell color is that Excel does not support all the colors which we usually pick through a color picker. To change the cell color through POI we need to pass a "short" data type value to the "style.setFillForegroundColor()" function. But who knows what value belongs to which color? I mean, can you guess which of CORNFLOWER_BLUE or LIGHT_CORNFLOWER_BLUE or LIGHT_BLUE or AQUA will look good on the cell? So here is the list of the values and the colors they resemble.
Labels:
Excel manipulation java,
hssf,
java color chart,
POI
Tuesday, December 15, 2009
CSS and Javascript Packing
While developing web applications, we use CSS and JS files. Now when the page opens, these get downloaded to the client side and take time doing so. Our aim should be that the size of these CSS/ JS files should be minimum so that the page opens up quickly. Here are a few links which help packing up these files.
1. Javascript Packing: http://dean.edwards.name/packer/
2. CSS Packing: http://www.cssdrive.com/index.php/main/csscompressor/
Amazing sites. Try the Base62 encode and shrink variable option in JS packing for better results.
1. Javascript Packing: http://dean.edwards.name/packer/
2. CSS Packing: http://www.cssdrive.com/index.php/main/csscompressor/
Amazing sites. Try the Base62 encode and shrink variable option in JS packing for better results.
Subscribe to:
Posts (Atom)
