Java : Crash without exception - java

I'm trying to debug some code that look like this :
class MyClass {
public void myMethod(HashMap<String, String> inputMap) {
try {
ConcurrentHashMap<String, String> cm = new ConcurrentHashMap<>();
cm.putAll(inputMap);
try {
for (Object key : cm.keySet()) {
cm.put(key.toString(), "");
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("After try catch");
} finally {
System.out.println("In finally");
}
}
}
By using the debugger in InteliJ I've figured out that this piece of code have an issue on the for loop line.
The execution pass from the for loop to the finally clause without passing in the catch clause neither the code after the try/catch.
The cm object isn't empty (there is around 30 elements in it).
I'm using java 7, System.getProperty("java.version") give 1.7.0_85
When I try to call the cm.keySet() mnually from the InteliJ debugger I have the following error message No such instance method: 'keySet'. But when I look at the javadoc of the ConcurentHashMap class this method should exists.
When I run cm.getClass().getDeclaredMethods() I see the method public java.util.Set java.util.concurrent.ConcurrentHashMap.keySet() in the methods list.
This code is not running on the main thread.
This don't display any error message in the console and I'm not able to catch an exception.
Does anyone have an idea of what could be the problem there? I've tried everything I could think of, and I'm out of options.
Edit problem fixed
The issue wasn't even in the code itself, it was that the compiler was updated from java 7 to java 8 without me noticing and without crashing during the compilation, while the java version that I use on my server was java 7. Since I didn't have the possibility to change neither the compiler version neither the version on the server, I've rewritten the code in another way so that it will work on both version.
It gives something like this :
class MyClass {
public void myMethod(HashMap<String, String> inputMap) {
try {
ConcurrentHashMap<String, String> cm = new ConcurrentHashMap<>();
cm.putAll(inputMap);
try {
Enumeration<String> keys = cm.keys();
while(keys.hasMoreElements()) {
String key = keys.nextElement();
cm.put(key, "");
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("After try catch");
} finally {
System.out.println("In finally");
}
}
}
Ps: Thank you, #cyberbrain, I wouldn't have figured this out without your advice on catching Throwable rather than Exception.

Try replacing Object with String
class MyClass {
public void myMethod(HashMap<String, String> inputMap) {
try {
ConcurrentHashMap<String, String> cm = new ConcurrentHashMap<>(inputMap);
try {
for (String key : cm.keySet()) {
cm.put(key, "");
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("After try catch");
} finally {
System.out.println("In finally");
}
}
}
You can also replace the entire for loop with the following:
cm.replaceAll((k, v) -> "");
edit: Realized lamdas wont work on JDK 1.7

Related

Activiti`s RuntimeServiceImpl::startProcessInstanceByKey cannot work well in a concurrent environment

I've got a very strange question in RuntimeServiceImpl::startProcessInstanceByKey.
The code is like this:
#Override
public String startProcessInstanceByKey(String processDefinitionKey, String businessKey,
String authenticatedUserId, Map < String, Object > variables) throws RiskManageException {
log.info("startProcessInstanceByKey,收到开启工作流 processDefinitionKey:{} ,businessKey:{},authenticatedUserId:{},variables:{}", //This can be printed normally
processDefinitionKey, businessKey, authenticatedUserId, JSON.toJSON(variables));
try {
Assert.notNull(authenticatedUserId, "userCode 不能为空");
Assert.notNull(processDefinitionKey, "流程定义key 不能为空");
processCoreService.getIdentityService().setAuthenticatedUserId(authenticatedUserId);
return processCoreService.getRuntimeService()
.startProcessInstanceByKey(processDefinitionKey, businessKey, variables).getProcessInstanceId(); //This statement didn`t execute
} catch (Exception e) {
throw new RiskManageException(ExceptionCodeEnum.START_PROCESS_ERROR, e); //Here throws an exception but the caller didn`t catch any
}
}
The process instance couldn't be created sometimes in a concurrent environment without any exception. It often happens when JDBC connections are about to use up. I want to know more detailed information, what should I do?

How to start some searches at the same time

I'm currently working on a frontend for visualizing the results out ouf some searches in foreign systems. At the moment the programm is asking one system by another and only continues, when alle foreign systems have answered.
The frontend is written in Vaadin 13 and this should be able to refresh the page by push.
I have six controller classes for six foreign systems to question and want to start all questions at the same time without having to wait for the privious controller to finish.
My problem is that I can't find a tutorial which helps me with this special problem. All tutorials are about starting the same process for more than once but at the same time.
This is how I start the searches at the moment:
public static void performSingleSearch(ReferenceSystem referenceSystem, String searchField, List<String> searchValues, SystemStage systemStage) throws Exception {
if(!isAvailable(referenceSystem, systemStage)) return;
Map<String, ReferenceElement> result = new HashMap<>();
try {
Class<?> classTemp = Class.forName(referenceSystem.getClassname());
Method method = classTemp.getMethod("searchElements", String.class , List.class, SystemStage.class);
result = (Map<String, ReferenceElement>) method.invoke(classTemp.newInstance(), searchField, searchValues, systemStage);
} catch (Exception e) {
return;
}
if(result != null) orderResults(result, referenceSystem);
}
I hope you can provide me an tutorial on how to, or better a book over multithreading.
Best regards
Daniel
Seems to me the simplest approach is using CompletableFuture. Ignoring your atrocious use of reflection, I'm going to assume
interface ReferenceSystem {
public Map<String,ReferenceElement> searchElements(List<String> args);
}
List<ReferenceSystem> systems = getSystems();
List<String> searchArguments = getSearchArguments();
so you can do
List<CompletableFuture<Map<String, ReferenceElement>>> futures = new ArrayList<>();
for (ReferenceSystem system : systems) {
futures.add(CompletableFuture.supplyAsync(() -> system.searchElements(searchArguments)));
}
or with Java 8 Streams
List<CompletableFuture<Map<String, ReferenceElement>>> futures =
systems.stream()
.map(s -> CompletableFuture.supplyAsync(
() -> system.searchElements(searchArguments)))
.collect(Collectors.toList());
Now the futures contains a list of futures which will eventually return the Map you're looking for; you can access them with #get() which will block until the result is present:
for (CompletableFuture<Map<String,ReferenceElement>> future : futures) {
System.out.printf("got a result: %s%n", future.get());
}
With your primitive case all you would need is either list of threads and just wait on them to finish or even easier, use thread pool and use that:
private static ExecutorService service = Executors.newFixedThreadPool(6); // change to whatever you want
public static void someMethod() {
queueActions(Arrays.asList(
() -> {
try {
performSingleSearch(null, null, null, null); // fill your data
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
},
() -> {
try {
performSingleSearch(null, null, null, null); // fill your data #2 etc
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
));
}
public static void queueActions(List<Runnable> actions) {
Semaphore wait = new Semaphore((-actions.size()) + 1);
for (Runnable action : actions) {
service.execute(() -> {
try {
action.run();
} finally {
wait.release();
}
});
}
try {
wait.acquire();
} catch (InterruptedException e) {
}
}
The question remains whether you want to orders be executed at the same time or one at a time or something else (join orders into one big order etc).

Handling exceptions while returning values by Optional flatmap

I have tried implementing Optional from JAVA in the below code. getOrders() method throws a KException.
#Override
public Optional<List<Order>> getPendingOrders(AuthDTO authDTO) throws MyException {
List<Order> orders=null;
try {
Optional<KConnect> connection = connector.getConnection(authDTO);
if (connection.isPresent()) {
orders = connection.get().getOrders();
}
}catch (KException e){
throw new MyException(e.message,e.code);
}
return Optional.ofNullable(orders);
}
I tried to remove the isPresent() check and replace it with flatmap.
#Override
public Optional<List<Order>> getPendingOrders(AuthDTO authDTO) throws MyException {
return connector.getConnection(authDTO).map(p -> {
try {
return p.getOrders();
} catch (KException e) {
throw new MyException(e.message,e.code); // [EXP LINE]
}
});
}
In this case I am not able to catch KException and convert it to MyException. My code won't compile.
unreported exception com.myproject.exception.MyException; must be caught or declared to be thrown
1st snippet works perfectly fine for me. Is there a better way to do this? Please suggest.
Edit: This does not change if I make it map instead of flatmap.
The exact problem is that IntelliJ is saying unhandled exception: com.myproject.exception.MyException at [EXP LINE] even though the method has throws MyExpception present.

How to not catch a particular line exception in try catch box in JAVA?

Here is my code:
whatever exception it throws I don't want to catch it outside, I want to continue my loop again by handling it separately. I don't want to use another try catch inside this try catch. Can someone guide me on this?
I don't want to use another try catch inside this try catch.
Yes you do.
MarketplaceBO marketplaceBOObject = new MarketplaceBO(entity.getMarketplaceID());
try {
marketplaceBOObject.loadFromSable();
} catch (WhateverException e) {
// Do something here, or, if you prefer, add the exception to a list and process later
doSomething() ;
// Continue your loop above
continue ;
}
if (marketplaceBOObject.isActive()) {
If you REALLY don't want to do this, your loadFromSable() method could return some object that provides information about success/failure of the call. But I wouldn't recommend that.
do this way -- this way your rest of the code will run no matter there is an exception or not
for (MerchantMarketplaceBO entity : merchantMarketplaceBOList) {
MarketplaceBO marketplaceBOObject = new MarketplaceBO(entity.getMarketplaceID());
try{
marketplaceBOObject.loadFromSable();
if (marketplaceBOObject.isActive()) {
resultVector.add(marketplaceBOObject.getCodigoMarketplace());
}
}
catch{
if (marketplaceBOObject.isActive()) {
resultVector.add(marketplaceBOObject.getCodigoMarketplace());
}
}
}
Another "trick" to deal with that is to move the body to the loop into a separate method having the "additional" try/catch block:
private MarketplaceBO loadFromSable(MerchantMarketplaceBO entity){
MarketplaceBO marketplaceBOObject = new MarketplaceBO(entity.getMarketplaceID());
try {
marketplaceBOObject.loadFromSable();
} catch (WhateverException e) {
// do something to make marketplaceBOObject a valid object
// or at least log the exception
}
return marketplaceBOObject;
}
But since we want to stick to the Same Layer of Abstraction principle we also need to move other part of that method to new smaller methods:
public void serveFromSableV2() {
String merchantCustomerID = ObfuscatedId.construct(request.getMerchantCustomerID()).getPublicEntityId();
try {
List<MerchantMarketplaceBO> merchantMarketplaceBOList =
getAllMerchantMarketplacesBOsByMerchant();
Vector<Marketplace> resultVector = new Vector<>();
for (MerchantMarketplaceBO entity : merchantMarketplaceBOList) {
MarketplaceBO marketplaceBOObject = loadFromSable(entity);
addToActiveMarketplacesList(marketplaceBOObject,resultVector);
}
verifyHavingActiveMarketPlaces(resultVector);
setResponseWithWrapped(resultVector);
} catch (EntityNotFoundException | SignatureMismatchException | InvalidIDException e) {
throw new InvalidIDException("merch=" + merchantCustomerID + "[" + request.getMerchantCustomerID() + "]"); //C++ stack throws InvalidIDException if marketplace is not found in datastore
}
}
You could refactor the load into a separate method that catches and returns the exception instead of throwing it:
private Optional<Exception> tryLoadFromSable(MarketplaceBO marketplaceBOObject) {
try {
marketplaceBOObject.loadFromSable();
return Optional.empty();
}
catch(Exception e) {
return Optional.of(e);
}
}
Then inside your loop:
//inside for loop...
MarketplaceBO marketplaceBOObject = new MarketplaceBO(entity.getMarketplaceID());
Optional<Exception> loadException = tryLoadFromSable(marketplaceBOObject);
if(loadException.isPresent()) {
//Do something here, log it, save it in a list for later processing, etc.
}

Java exception handling in non sequential tasks (pattern/good practice)

There are some task that should't be done in parallel, (for example opening a file, reading, writing, and closing, there is an order on that...)
But... Some task are more like a shoping list, I mean they could have a desirable order but it's not a must..example in communication or loading independient drivers etc..
For that kind of tasks,
I would like to know a java best practice or pattern for manage exceptions..
The java simple way is:
getUFO {
try {
loadSoundDriver();
loadUsbDriver();
loadAlienDetectorDriver();
loadKeyboardDriver();
} catch (loadSoundDriverFailed) {
doSomethingA;
} catch (loadUsbDriverFailed) {
doSomethingB;
} catch (loadAlienDetectorDriverFailed) {
doSomethingC;
} catch (loadKeyboardDriverFailed) {
doSomethingD;
}
}
But what about having an exception in one of the actions but wanting to
try with the next ones??
I've thought this approach, but don't seem to be a good use for exceptions
I don't know if it works, doesn't matter, it's really awful!!
getUFO {
Exception ex=null;
try {
try{ loadSoundDriver();
}catch (Exception e) { ex=e; }
try{ loadUsbDriver();
}catch (Exception e) { ex=e; }
try{ loadAlienDetectorDriver();
}catch (Exception e) { ex=e; }
try{ loadKeyboardDriver()
}catch (Exception e) { ex=e; }
if(ex!=null)
{ throw ex;
}
} catch (loadSoundDriverFailed) {
doSomethingA;
} catch (loadUsbDriverFailed) {
doSomethingB;
} catch (loadAlienDetectorDriverFailed) {
doSomethingC;
} catch (loadKeyboardDriverFailed) {
doSomethingD;
}
}
seems not complicated to find a better practice for doing that.. I still didn't
thanks for any advice
Consider the execute around idiom.
Another option (which isn't really all that different, it just decouples them more) is to do each task in a separate thread.
Edit:
Here is the kind of thing I have in mind:
public interface LoadableDriver {
public String getName();
public void loadDriver() throws DriverException;
public void onError(Throwable e);
}
public class DriverLoader {
private Map<String, Exception> errors = new HashMap<String, Exception>();
public void load(LoadableDriver driver) {
try {
driver.loadDriver();
} catch (DriverException e) {
errors.put(driver.getName(), e);
driver.onError(e);
}
}
public Map<String, Exception> getErrors() { return errors; }
}
public class Main {
public void loadDrivers() {
DriverLoader loader = new DriverLoader();
loader.loadDriver(new LoadableDriver(){
public String getName() { return "SoundDriver"; }
public void loadDriver() { loadSoundDriver(); }
public void onError(Throwable e) { doSomethingA(); }
});
//etc. Or in the alternative make a real class that implements the interface for each driver.
Map<String, Exception> errors = loader.getErrors();
//react to any specific drivers that were not loaded and try again.
}
}
Edit: This is what a clean Java version would ultimately look like if you implemented the drivers as classes (which is what the Java OO paradigm would expect here IMHO). The Main.loadDrivers() method would change like this:
public void loadDrivers(LoadableDriver... drivers) {
DriverLoader loader = ...
for(LoadableDriver driver : drivers) {
loader.load(driver);
}
//retry code if you want.
Set<LoadableDriver> failures = loader.getErrors();
if(failures.size() > 0 && tries++ > MAX_TRIES) {
//log retrying and then:
loadDrivers(drivers.toArray(new LoadableDriver[0]));
}
}
Of course I no longer use a map because the objects would be self-sufficient (you could get rid of the getName() method as well, but probably should override toString()), so the errors are just returned in a set to retry. You could make the retry code even simpler if each driver was responsible for knowing how often it should it retry.
Java won't look as nice as a well done C++ template, but that is the Java language design choice - prefer simplicity over complex language features that can make code hard to maintain over time if not done properly.
Try this:
protected void loadDrivers() {
loadSoundDriver();
loadUsbDriver();
loadAlienDetectorDriver();
loadKeyboardDriver();
}
Then:
protected void loadSoundDriver() {
try {
// original code ...
}
catch( Exception e ) {
soundDriverFailed( e );
}
}
protected void soundDriverFailed( Exception e ) {
log( e );
}
This gives subclasses a chance to change the behaviour. For example, a subclass could implement loading each driver in a separate thread. The main class need not care about how the drivers are loaded, nor should any users of the main class.
IMO, for your case, if the exception is "ignorable" it's best if the "loadSoundDriver" method catches the exception and simply returns an error.
Then in the function that loads stuff, you can record all the errors and at the end of the sequence, decide what to do with them.
[edit]
Something like this:
// init
MyError soundErr = loadSoundDriver();
MyError otherErr = loadOtherDriver();
if(soundErr!=null || otherErr !=null){
// handle the error(s)
}
Just surround every single load operation with its own try / catch block.
try {
loadSoundDriver();
} catch (loadSoundDriverFailed) {
doSomethingA;
}
try {
loadUsbDriver();
} catch (loadUsbDriverFailed) {
doSomethingB;
}
// ...
So you can handle every exception by itself and continue processing the oder operations.

Categories

Resources