Usage of "(!Oracle.acquireLockNoWait)" - java

private void acquireEtlLock() throws StepwiseException {
try {
if (!Oracle.acquireLockNoWait(this.context.getConnection(), getProcessLockName())) {
throw new StepwiseException("Another session is in progress for process: "
+ this.context.getSession().getProcessName());
}
this.isLockAcquired = true;
} catch (SQLException e) {
throw new StepwiseException("Error acquiring session lock for process: "
+ this.context.getSession().getProcessName(), e);
}
}
I would like to know the exact functionality of "!Oracle.acquireLockNoWait", actually this is a method to call a cron job, but for some reason i dont find the job to be running. So just wanted to check if this code could cause a block or a deadlock.
I am receiving the error "Another session is in progress for process: ", what could be the possible reasons for this?

Related

Java 8: Kill/Stop a thread after certain period of time

I have a java 8 based project which performs a certain function on a url. I need to modify the code snippet below so that it is capable of killing the thread/process running and run the next instance after a certain period of time irrespective of current process status.
I tried the following techniques to implement the thread kill procedure:
Executor service
Timer Task
Multithreaded thread kill
The code snippet for my most recent attempt is linked below.
#SuppressWarnings("static-access")
public static void main(String[] args) {
//fetch url from the txt file
List<String> careerUrls = getCareerUrls();
int a = 0;
DBConnection ds = null;
ds = DBConnection.getInstance();
try (java.sql.Connection con = ds.getConnection()) {
//read a single Url
for (String url : careerUrls) {
int c = a++;
ExecutorService executor = Executors.newFixedThreadPool(3);
Future<?> future = executor.submit(new Runnable() {
#Override
// <-- job processing
public void run() {
long end_time = System.currentTimeMillis() + 10000;
System.out.println("STARTED PROCESSING URL: " + url);
jobareaDeciderSample w = new jobareaDeciderSample();
w.mainSample(url, c, con);
}
});
// <-- reject all further submissions
executor.shutdown();
try {
future.get(120, TimeUnit.SECONDS); // <-- wait 2 Minutes to finish
} catch (InterruptedException e) { // <-- possible error cases
System.out.println("job was interrupted");
future.cancel(true);
Thread.currentThread().interrupt();
;
} catch (ExecutionException e) {
System.out.println("caught exception: " + e.getCause());
} catch (TimeoutException e) {
System.out.println("timeout");
future.cancel(true);
}
// wait all unfinished tasks for 2 sec
if (!executor.awaitTermination(0, TimeUnit.SECONDS)) {
// force them to quit by interrupting
executor.shutdownNow();
}
}
} catch (Exception e) {
LOGGER.error(e);
}
}
You are correct with your approach.
calling cancel(true); on future is the right way to stop this task.
You have another problem- you cannot just stop a thread. (well you can, using stop() in thread class, but you should never do this).
cancel(true); sends information to the thread, that it should be stopped. Some java classes are responding to this information and throw interrupted exception. But some dont. You have to modify your task code, to check if Thread.currentThread().isInterrupted(), and if so, stop execution.
This is something you have to do in your code, which you call by
jobareaDeciderSample w = new jobareaDeciderSample();
w.mainSample(url, c, con);
You should do this in some long time spinning code, if you said you do some stuff with url, you should do it in your while loop, where you download information for the web. In other words, do this check only when your code spends 99% of the time.
Also you are calling
Thread.currentThread().interrupt();
in your main thread, this does not do anything for you, as if you want to quit current thread, you can just call return

Best practice - Generic webdriverWait till loading popup exist, if error appears fail the test

My problem is I have customWaitMethods such as:
public void waitForLoading(WebElement loadingElement, WebElement errorElement) {
long timeOut = Long.parseLong(PropertyReader.getInstance().getProperty("DEFAULT_TIME_OUT"));
try {
WebDriverWait wait = new WebDriverWait(DriverFactory.getInstance().getDriver(), timeOut);
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.id(loadingElement.toString())));
if (errorElement.isDisplayed()) {
throw new TestException();
}
} catch (TimeoutException e) {
System.out.println("Timed out after default time out");
} catch (TestException e) {
System.out.println("Unexpected error occurred, environment error");
e.printStackTrace();
}
}
I need some generic customWait methods. I do a search, but several cases need to be handled. Error msg appear -> fail the test. wait for the loading content, and it disappeared, -> check the search result.
How can I extend this code if I would like to check continuously some error_message element appears as well and in this case I would throw an exception? So independently I can handle the timeout exception and the other, error msg?
This sript is failing because of the IF. ErrorElement does not appear on the page, ---> nosuchelementException
You can catch different Exceptions as you see fit. In your case, you want to catch the TimeoutException to handle time outs. Then catch a different type of exception to handle the error message:
public void waitForLoading() {
long timeOut = Long.parseLong(...);
try {
WebDriverWait wait = new WebDriverWait(...);
wait.until(ExpectedConditions.invisibilityOfElementLocated(...));
if (<error-message-appears>) {
throw new CustomErrorMessageAppearedException();
}
} catch (TimeoutException e) {
System.out.println("Timed out after...");
} catch (CustomErrorMessageAppearedException e) {
// handle error message
}
}
The easiest approach I see is:
public void waitForLoading() {
long timeOut = Long.parseLong(PropertyReader.getInstance().getProperty("DEFAULT_TIME_OUT"));
try {
WebDriverWait wait = new WebDriverWait(DriverFactory.getInstance().getDriver(), timeOut);
if (!wait.until(ExpectedConditions.invisibilityOfElementLocated(By.id("wait_element")));)
{
throw new NoSuchElementException();
}
} catch (TimeOutException e) {
System.out.println("Timed out after " + timeOut + "seconds waiting for loading the results.");
}
}

Why dosnt my method catch my 'Timeout Exception' and print to console?

Why dosnt my method catch my 'Timeout Exception' and print to console?
public void clickDrivingExperienceButton() throws Exception {
boolean test = this.wait.until(ExpectedConditions.elementToBeClickable(link_DrivingExperiences)).isEnabled();
try {
if (test == true) {
link_DrivingExperiences.click();
}
System.out.println("Successfully clicked on the driving experience button, using locator: " + "<" + link_DrivingExperiences.toString() + ">");
}catch (TimeoutException e) {
System.out.println("WHY DONT I PRINT ANYTHING??????" + e.getMessage());
}catch (Exception e) {
System.out.println("Unable to click on the Driving Experience Button, Exception: " + e.getMessage());
} finally {
// final code here
}
}
Most likely timeout exception throws out of this.wait.until(ExpectedConditions.elementToBeClickable(link_DrivingExperiences)).isEnabled();, and your try-catch block doesn't enclose that line
Put this.wait.until inside try block.
Exception message already tells that the exception occurred when it was waiting for the element to be clickable.
public void clickDrivingExperienceButton() throws Exception {
try {
boolean test = this.wait.until(ExpectedConditions.elementToBeClickable(link_DrivingExperiences)).isEnabled();
if (test == true) {
link_DrivingExperiences.click();
}
System.out.println("Successfully clicked on the driving experience button, using locator: " + "<" + link_DrivingExperiences.toString() + ">");
}catch (TimeoutException e) {
System.out.println("WHY DONT I PRINT ANYTHING??????" + e.getMessage());
}catch (Exception e) {
System.out.println("Unable to click on the Driving Experience Button, Exception: " + e.getMessage());
} finally {
// final code here
}
}
Your try-catch isn't catching the exception because the exception comes from the 2nd line (wait.until) and that's not inside the try-catch.
You've got many of the same issues that I addressed in your other question, https://stackoverflow.com/a/42120129/2386774, that I would suggest that you fix up in this code also.
It should basically be the below
public void clickDrivingExperienceButton() throws Exception
{
this.wait.until(ExpectedConditions.elementToBeClickable(link_DrivingExperiences)).click();
}
You shouldn't really need to log as much as you are logging. If the element is successfully clicked, the script will progress. Logging that is just going to clog up your logs, IMO. There's also no point in logging an exception because it's going to be dumped to the logs anyway. Generally, you want your script to stop when an exception is thrown unless proceeding won't be affected by it. That largely depends on your scenario so you will have to make the final decision on whether to proceed or not which will determine how you handle thrown exceptions.

debugging multiThreads in intellij: how can i see the all thrown exceptions?

I have a multithreaded code in java.
I debug with intellij. I know how to switch debug contexts between threads.
Nevertheless the console shows only exception thrown for the main thread.
How can i see the exceptions thrown from any thread?
basically when I run integration test with an Executor, some exception is thrown from secondary thread.
But nothing is printed to the debug-console.
Actually the the code flies and never reach to the try catch i have.
It's like I cannot step-next after the code that throws an exception
try {
while (true) {
logger.debug("New thread. polling on DB, polling on deployment service");
ConfigAction configAction = configActionFactory.get(ConfigActionsEnum.PushToDeployment);
while (configAction != null) {
configAction = configAction.execute() ? configAction.nextActivity() : null;
}
}
} catch (Exception e) {
e.printStackTrace();
logger.error("DeploymentContextListener run failed", e);
}
whereas when I run with the main thread, the same code I see the exception:
public void run() {
try {
while (true) {
logger.debug("New thread. polling on DB, polling on deployment service");
ConfigAction configAction = configActionFactory.get(ConfigActionsEnum.PushToDeployment);
while (configAction != null) {
configAction = configAction.execute() ? configAction.nextActivity() : null;
}
}
} catch (Exception e) {
e.printStackTrace();
logger.error("DeploymentContextListener run failed", e);
}
it is written in one of the try-catch i have
} catch (Exception ex) {
logger.error("failed to get from DB: getLatestConfigVersionWaitingForDeploy", ex);
}
My problem was that i used:
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> { }
from what I have read:
invokeAll - call “future.get()”. Wait for all threads to finish.
Submit -> attach the errors to Future objects, not the the std-error
Execute -> the errors are thrown to the std-error

Java invoke thread inside it's run()

I wrote a thread class that checks the socket connection to the server by sending a small string every one second.
begin() method executes the thread.
After connection is lost, the thread tries to connect again.
My question is if it's ok to re-run by begin() the thread inside the run() method like I did (see below).
public void begin() {
Check = new Thread(this);
Check.start();
}
#Override
public void run() {
Thread thisThread = Thread.currentThread();
while (Check==thisThread) {
try {
oos.writeObject("a");
// oos.flush();
synchronized (this) {
while (pleaseWait) {
try {
System.out.println("waiting");
wait();
System.out.println("not waiting");
}
catch (Exception e) {
System.err.println("Thread is interrupted: "+e.getMessage());
}
}
}
sleep(1000);
} catch (Exception ex) {
v = new Visual("The connection is lost. The system will try to reconnect now.");
this.end();
try {
Server=ClientLogin.checkingServers(); //returns the reachable server string address
socket = new Socket(Server, ServerPort);
System.out.println("Connected: " + socket);
oos = new ObjectOutputStream(socket.getOutputStream());
begin();
v = new Visual("The system is reconnected.");
}
catch(UnknownHostException uhe){
System.out.println("Host unknown: " + uhe.getMessage());
v = new Visual("The system has failed to reconnected.");
}
catch (IOException ioe) {
System.out.println("The system cannot connect to servers: " + ioe.getMessage());
v = new Visual("The system has failed to reconnected.");
}
catch (Exception e) {
System.out.println("The system has failed to reconnect: " + e.getMessage());
v = new Visual("The system has failed to reconnected.");
}
}
}
}
public void end() {
Check = null;
}
I don't know any reason why that wouldn't work, but it looks kinda messy. You may have to declare Check as volatile to ensure that the loop always reads the current value, for those times when the new thread overwrites it.
IMHO a better approach would be a separate "supervisor" thread which is responsible for starting one of these threads, and then uses Thread.join() to wait for it to die, at which point it can start it up again.
In this way your main thread's logic can concentrate on exactly what it's supposed to do, without needing to have any "self awareness".
First, the code is not thread safe. The "Check" field is written by one thread but read by another, but it is not synchronised. There is no guarantee that the new started thread is going to see the updated value of "Check", i.e. the new thread will get the old thread's reference when checking "Check==thisThread" and do the wrong thing,
This particular problem can be fixed by making "Check" field volatile. It makes sure when it is updated, every thread will see the new value.
It is not "wrong" to call "begin()" in the run() method. However I wouldn't recommend it because you created a recursive call here effectively. There is a good chance you will get it wrong and fall into infinite loop. Try the simple design below. It uses a while loop instead of recursion.
package com.thinkinginobjects;
public class HeathChecker {
public void run() {
while (true) {
boolean success = checkHeath();
if (!success) {
//log and re-establish connection
} else {
Thread.sleep(1000);
}
}
}
private boolean checkHeath() {
try {
oos.writeObject("a");
return true;
} catch (Exception ex) {
return false;
}
}
}
it is ok, however why do you need to start a thread every time? Isn't it better to use Timer and TimerTask?
http://docs.oracle.com/javase/6/docs/api/java/util/TimerTask.html
http://docs.oracle.com/javase/6/docs/api/java/util/Timer.html

Categories