My abandon() may throw AbandonException.
While handling the exception I have to recall the same method if there some element left in the Vector.
How should I proceed? And if I am not thinking straight, what would be the best solution?
if (i + 1 < lc.size()) {
try {
lc.get(i + 1).abondon();
}
catch (AbandonException e1) {
lc.get(i+2).abandon();}}
following is some pseudo-code:
List errorIndexList = new ArrayList();
for(...) {
if (i + 1 < lc.size()) {
try {
lc.get(i + 1).abondon();
} catch (AbandonException e1) {
errorIndexList.add(i+1);
// do some error handle work ..
// print error log/info if need,
continue; // this is optional, in case it's the last statement,
}
}
}
// use errorIndexList to handle your errors, if need,
You could use finally here.
try {
lc.get(i + 1).abondon();
}
catch (AbandonException e1) {
} finally {
your code
}
Related
In Kotlin code, I have a list of objects and while processing it via filter and map I want to collect items of particular interest. And discard others.
For example, I am using foreach loop as below. Is it possible to make it better by using map instead of foreach?
fun main() {
val exceptionRequests = mutableListOf<String>()
listOf<String>("Name1", "Name2", "Name3")
.filter {
it.length > 2
}
.forEach {
try {
if (it == "Name2") {
throw Exception(it)
} // Throwing exception here like this for simplicity. In real case, business logic throws exception.
} catch (exception: Exception) {
exceptionRequests.add(it)
}
}
println(exceptionRequests) // This prints `Name2`.
}
You can use .mapNotNull
val exceptionResults = listOf<String>("Name1", "Name2", "Name3")
.filter {
it.length > 2
}
.mapNotNull { name ->
try {
if (name == "Name2") {
throw Exception(name)
}
null
} catch (exception: Exception) {
name
}
}
println(exceptionRequests) // This prints `Name2`.
If exception isn't thrown, try catch expression will result in null.
If exception is thrown, try catch expression will result in name.
mapNotNull will filter out nulls (cases where exception wasn't thrown).
Why do you compare it and throw an Exception and then add that in the catch block?
You can derive exceptionRequests as follow:
val exceptionRequests = listOf<String>("Name1", "Name2", "Name3")
.filter {
it.length > 2 && it == "Name2"
}
I am trying to find count of rows in all tables of a database on source and destination, source being Greenplum and destination being Hive(on HDFS).
To do the parallel processing, I have created two threads which calls the methods that calculate the counts on both the ends independently. The code can be seen below:
new Thread(new Runnable() {
#Override
public void run() {
try {
gpTableCount = getGpTableCount();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
#Override
public void run() {
try {
hiveTableCount = getHiveTableCount();
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
while(!(gpTableCount != null && gpTableCount.size() > 0 && hiveTableCount != null && hiveTableCount.size() > 0)) {
Thread.sleep(5000);
}
The results of both the threads are stored in two separate Java Hashmaps.
Below is the count for calculating the GP counts. Method of calculating Hive counts is same except the database name, hence I just gave one method.
public Map<String,String> getGpTableCount() throws SQLException {
Connection gpAnalyticsCon = (Connection) DbManager.getGpConnection();
while(keySetIterator_gpTableList.hasNext()) {
gpTabSchemakey = keySetIterator_gpTableList.next();
tablesnSSNs = gpTabSchemakey.split(",");
target = tablesnSSNs[1].split(":");
analyticsTable = target[0].split("\\.");
gpCountQuery = "select '" + analyticsTable[1] + "' as TableName, count(*) as Count, source_system_name, max(xx_last_update_tms) from " + tablesnSSNs[0] + " where source_system_name = '" + target[1] + "' group by source_system_name";
try {
gp_pstmnt = gpAnalyticsCon.prepareStatement(gpCountQuery);
ResultSet gpCountRs = gp_pstmnt.executeQuery();
while(gpCountRs.next()) {
gpCountRs.getLong(2) + ", Max GP Tms: " + gpCountRs.getTimestamp(4).toString());
gpDataMap.put(gpCountRs.getString(1) + "," + gpCountRs.getString(3), gpCountRs.getLong(2) + "," + gpCountRs.getTimestamp(4).toString());
}
} catch(org.postgresql.util.PSQLException e) {
e.printStackTrace();
} catch(SQLException e) {
e.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}
}
System.out.println("GP Connection closed");
gp_pstmnt.close();
gpAnalyticsCon.close();
return gpDataMap;
}
Hive's Method:
public Map<String, String> getHiveTableCount() throws IOException, SQLException {
Connection hiveConnection = DbManager.getHiveConnection();
while(hiveIterator.hasNext()) {
gpHiveRec = hiveIterator.next();
hiveArray = gpHiveRec.split(",");
hiveDetails = hiveArray[1].split(":");
hiveTable = hiveDetails[0].split("\\.");
hiveQuery = "select '" + hiveTable[1] + "' as TableName, count(*) as Count, source_system_name, max(xx_last_update_tms) from " + hiveDetails[0] + " where source_system_name='" + hiveDetails[1] + "' group by source_system_name";
try {
hive_pstmnt = hiveConnection.prepareStatement(hiveQuery);
ResultSet hiveCountRs = hive_pstmnt.executeQuery();
while(hiveCountRs.next()) {
hiveDataMap.put(hiveCountRs.getString(1) + "," + hiveCountRs.getString(3), hiveCountRs.getLong(2) + "," + hiveCountRs.getTimestamp(4).toString());
}
} catch(HiveSQLException e) {
e.printStackTrace();
} catch(SQLException e) {
e.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}
}
return hiveDataMap;
}
When the jar is submitted, both the threads are launched and the SQL Queries for GP & Hive start executing simultaneously.
But the problem here is, as soon as the thread for GP finishes the execution of the method: getGpTableCount(), I see the print statement: GP Connection closed and the hive's thread hangs for atleast 30mins before resuming.
If checked for locks on Hive tables incase there would be none locked. After 30-40mins, the hive threads starts again and finishes. This happens even for less number of tables (like 20 tables) on hive.
This is how I submit the jar:
/usr/jdk64/jdk1.8.0_112/bin/java -Xdebug -Dsun.security.krb5.debug=true -Djava.security.krb5.conf=/etc/krb5.conf -Djava.security.krb5.realm=PROD.COM -Djava.security.krb5.kdc=ip-xx-xxx-xxx-xxx.ec2.internal -Djavax.security.auth.useSubjectCredsOnly=false -jar /home/etl/ReconTest/ReconAuto_Test_Prod.jar
Could anyone let me know if there is any issue with the way I create threads in the code and how can I fix it ?
Assuming your gpTableCount and hiveTableCount are normal HashMaps, you're running in to synchronization issues.
This is a broad topic to fully explain here, but here's a short intro:
Since they are populated in different threads, your main thread does not 'see' these changes until the memory is synchronized. There's no guarantee when this happens (and it's best to assume it will never happen unless you force it).
To do this properly, either use threadsafe versions (see Collections.synchronizedMap or ConcurrentHashMap), or manually synchronize your checks on the same monitor. (i.e. but the check itself in a synchronized method, and put the code that populated the map in a synchronized method, too). Alternatively, you could put the count itself in two volatile ints, and update those in the other two threads.
I am fetching a course object by its course run id. Below is my code that works perfectly ok.
public static CourseVO getBlackboardCourseObjectByCourseRunID(String RunID){
CourseVO[] courseVOList = null;
try {
courseVOList = BlackboardCoursesDAO.getAllBlackBoardCourse();
} catch (RemoteException e) {
// TODO Auto-generated catch block
throw new RuntimeException("Not able to fetch blackboard courses");
}
CourseVO courseVO = new CourseVO();
int length=courseVOList.length;
System.out.println("length : "+length);
int i=0;
courseVO = courseVOList[i];
while(!courseVO.getId().equals(RunID) && i<length){
courseVO = courseVOList[i];
//System.out.println("in while loop ");
i++;
}
return courseVO;
}
But it troubles when I try to fetch this object in a loop.
If anyone can provide some better code, it will be great help.
Thanks.
After line 8, you can try to change lines with this>
Stream<CourseVO> courseList = Arrays.stream(courseVOList);
CourseVO foundCourse = courseList.filter(s -> s.getId().equals(RunID) )
.findFirst().get();
I'm getting results from a PHP, and parse them to a String array
ParseResults[0] is the ID returned from the database.
What I'm trying to do, is make a message box, which is only shown once (until the application is restarted of course).
My code looks something like this, but I can't figure out what stops it from working properly.
public void ShowNotification() {
try {
ArrayList<String> SearchGNArray = OverblikIntetSvar(Main.BrugerID);
// SearchGNArray = Gets undecoded rows of information from DB
for(int i=0; i<SearchGNArray.size(); i++){
String[] ParseTilArray = ParseResultater(SearchGNArray.get(i));
// ParseToArray = Parse results and decode to useable results
// ParseToArray[0] = the index containing the ID we'd like
// to keep track of, if it already had shown a popup about it
if (SearchPopUpArray.size() == 0) {
// No ID's yet in SearchPopUpArray
// SearchPopUpArray = Where we'd like to store our already shown ID's
SearchPopUpArray.add(ParseTilArray[0]);
// Create Messagebox
}
boolean match = false ;
for(int ii=0; ii<SearchPopUpArray.size(); ii++){
try {
match = SearchPopUpArray.get(ii).equals(ParseTilArray[0]);
} catch (Exception e) {
e.printStackTrace();
}
if(match){
// There is a match
break; // Break to not create a popup
} else {
// No match in MatchPopUpArray
SearchPopUpArray.add(ParseTilArray[0]);
// Create a Messagebox
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
As of now I have 2 rows, so there should be two ID's. There's 101 and 102. It shows 102 once, and then it just keeps creating messageboxes about 101.
You are not incrementing the right variable in the second for-loop:
for(int ii = 0; ii <SearchPopUpArray.size();i++){
/* ^
|
should be ii++
*/
}
It might be help to use more descriptive variable name like indexGN and indexPopup instead to avoid this sort of issue
I've deleted the second for loop:
for(int ii=0; ii<SearchPopUpArray.size(); ii++){
try {
match = SearchPopUpArray.get(ii).equals(ParseTilArray[0]);
} catch (Exception e) {
e.printStackTrace();
}
if(match){
// There is a match
} else {
// No match in MatchPopUpArray
SearchPopUpArray.add(ParseTilArray[0]);
// Create a Messagebox
}
}
And replaced with
if (SearchPopUpArray.contains(ParseTilArray[0])) {
// Match
} else {
// No match i MatchPopUpArray
SearchPopUpArray.add(ParseTilArray[0]);
// Create a Messagebox
}
Much more simple.
I've got the following code snippet that I'm thinking of refactoring to a more abstract application exception handler but I want to make sure I've got it as tidy as possible first
Any suggestions on how to improve this code or make it more resuable
int id = -1;
final StringBuilder errorMessage = new StringBuilder("Bad Input Value: ");
try {
id = Integer.parseInt(edtId.getText().toString());
} catch (final NumberFormatException e) {
errorMessage.append("Failed to parse id " + e.getMessage());
}
if (id < 0) {
errorToast(errorMessage.toString());
} else {
//go ahead an retreive values from database knowing the id has been parsed
//correctly to a positive int.
}
Why pre-assign id to a magic number?
try {
int id=Integer.parseInt(edtId.getText().toString());
//go on as normal
} catch (NumberFormatException e) {
//handle error
}