Why Thread.sleep can make the properties of class is visible? [duplicate] - java

This question already has answers here:
java when I invoked Thread.sleep(), the data's visibility
(2 answers)
What is the relationship between Thread.sleep and happens-before?
(4 answers)
Closed 22 days ago.
I want to know why Thread.sleep can change the result of this program.Thanks.
this is the question of mine.
When Thread.sleep is running, the program will stop. But else not.
public class Main {
boolean flag = true;
void stop(){
while(flag){
/*
this is the question of mine.
When Thread.sleep running , the programmer will stop . But else not.
*/
//try {
// TimeUnit.MILLISECONDS.sleep(1);
//}catch (Exception ex){
// ex.printStackTrace();
// }
}
System.out.println("over......");
}
public static void main(String[] args) {
Main main = new Main();
new Thread(main::stop).start();
try {
Thread.sleep(1000);
}catch (Exception ex){
ex.printStackTrace();
}
main.flag = false;
}
}

Related

Multithreading synchronized block giving random answer every time [duplicate]

This question already has answers here:
Why is Java synchronized not working as expected?
(3 answers)
Java synchronized block not working
(2 answers)
Closed 5 years ago.
i have created a JAVA prog to check the working of synchronized block . But it is giving random answers every time. Can anyone explain why it is behaving like that.
Program:
public class ThreadSyncex1 extends Thread {
public static void main(String[] args) {
call a=new call();
call b=new call();
a.start();
b.start();
try {
a.join();
b.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class call extends Thread {
public void run() {
System.out.println(System.currentTimeMillis());
synchronized(this)
{
try {
System.out.println(Thread.currentThread().getName());
System.out.println("Success...");
Thread.sleep(500);
} catch(Exception e){
System.out.println(e);
}
}
}
}
It is giving output :
1502683588129
1502683588129
Thread-1
Thread-0
Success...
Success...
and
1502683592249
1502683592249
Thread-1
Success...
Thread-0
Success...

Is there a nicer solution for (not) continuing after try catch in a method? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
Right now my solution looks like this:
public void method() {
int number;
boolean continue = true;
try {
number = parseInt(this.something);
} catch (NumberFormatException e) {
//some code
continue = false;
}
if (continue) {
//more code
}
}
Is there something prettier out there?
Is there a nicer solution for (not) continuing after try catch in a method?
The intended way is to write the code that should be skipped inside the try block:
public void method() {
try {
int number;
number = parseInt(this.something);
//more code
} catch (NumberFormatException e) {
// log exception
// do things to recover from the error if possible
// maybe rethrow `e` or throw another exception
}
// avoid to write some code here, usually it is wrong.
}
Even though it is a void method, you can use return; which then will exit the method. Therefore a perfectly fine solution to your "problem" is to just use return and removing the if as follows:
public void method() {
int number;
try {
number = parseInt(this.something);
} catch (NumberFormatException e) {
//some code
return;
}
//more code
}
If the object is not setup properly (this.something was not set), it might be better to throw then catch in the calling code. If you just return, the caller might assume the method completed successfully. Otherwise the code provided by Aidin would work.
You can simply ignore the exception and log the exception for information purpose:
public void method() {
int number;
try {
number = parseInt(this.something);
} catch (Exception ignored) {
// here could be some System.out.println or a logging API
}
}
But if you have a return, just return null and evaluate your result whether is null or not.
public Integer method() {
try {
return parseInt(this.something);
} catch (Exception ignored) {
// here could be some System.out.println or a logging API
}
return null;
}
Integer number = method();
if (number != null) {....
You could use retun; break; or possibly System.exit()

Try, catch and Exception handling [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Test class:
package learning;
import java.io.IOException;
import java.util.Scanner;
public class Test {
static Scanner user = new Scanner(System.in);
public static void main(String[] args) {
Test2 t = new Test2();
try {
t.run(0);
} catch (Exception e) {
try {
t.run(user.nextInt());
} catch (Exception ee) {
try {
t.run(user.nextInt());
} catch (Exception dd) {}
}
}
}
}
Test2 class:
package learning;
import java.io.IOException;
public class Test2 extends Test {
public int x = 0;
public void run(int a) throws Exception, IOException {
do {
if (a > 1)
System.out.println(a);
x = x + 1;
if (a < 1) {
System.out.println("you're wrong");
throw new Exception();
}
} while (x==0);
}
}
It will stop running if a > 0, but when I answer with a string it will also stop running. How do I get the program to ask again and if I enter 2 times a number below 1 it will also stop running how do I make it endless?
Easiest way to make anything endless is to throw a while(true) loop on it. Better programming practices may include properly disposing by doing while(started) and setting started to false.
In your case I am not sure what you intention is... so the following should work. Also get rid of that do while loop. To be honest this code can totally be written cleaner but you can just play around for now.
public class Test {
static Scanner user = new Scanner(System.in);
public static void main(String[] args) {
Test2 t = new Test2();
while(true) {
try {
t.run(user.nextInt());
Thread.Sleep(50);
} catch (Exception e) {
}
}
}

Is it deadlock? Why it happens? [duplicate]

This question already has answers here:
Program hangs if thread is created in static initializer block
(4 answers)
Closed 8 years ago.
Can someone explain to me why the following code prints nothing?
When I tried to debug it, the debugger froze on the line t.join();. But in the debugger I saw the message: "program is running".
public class Main_problem1_multithreading {
private static boolean initialized = false;
static {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
initialized = true;
}
});
t.start();
try {
t.join();
} catch (InterruptedException e) {
throw new AssertionError(e);
}
}
public static void main(String[] args) {
System.out.println(initialized);
}
}
Static initialization takes place when JVM loads a class first time. The thread that loads the class has a lock on Static Initializer , In this case main thread is already holding the lock.
Until that lock is released the newly spawned thread cannot access "initialized" variable.
You can clearly see in the image I attached. Thread - 0 is stepping at line 10. Line 10 is where new thread tries to update initialized variable. So this new thread keep waiting for the lock which it never gets and main thread keeps waiting for new thread to join it. Deadlock!! Hope it helps!
package com.test;
public class Test {
private static boolean initialized = false;
static {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
initialized = true;
System.out.println("New Thread" + initialized);
}
});
t.start();
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
System.out.println("Main Thread" + initialized);
}
}

Regarding excuting finally block in system.exit case also by adding shutdownhook [duplicate]

This question already has answers here:
How does Java's System.exit() work with try/catch/finally blocks? [duplicate]
(6 answers)
Closed 9 years ago.
I have developed a program in which the case of return statement either inside try block or catch block the finally block executes at last but when I write system.exit inside try block in this case the finally block not executed but still I want to execute , could you please advise do I need to add Runtime.getRuntime().addShutdownHook in that case I need to add the code that should be executed in any case , even if system.exit is called. please advise , below is my class
public class Hello {
public static void hello(){
try{
System.out.println("hi");
System.exit(1);
// return;
}catch(RuntimeException e)
{ //return;
}
finally{
System.out.println("finally is still executed at last");
}
}
public static void main(String[] args){
Hello.hello();
}
}
1) in general you do need a shutdown hook if you want to execute some code after exit
public static void main(String[] args) throws Exception {
Runtime.getRuntime().addShutdownHook(new Thread() {
#Override
public void run() {
System.out.println("bye");
}
});
hello();
}
2) in this concrete case there's no need for shutdown hook, just remove exit from the code
public static void hello() {
try{
System.out.println("hi");
} catch (RuntimeException e) {
//
} finally{
System.out.println("finally is still executed at last");
}
}
when you are calling System.exit(1)
it exits your program and JVM stops the execution of your program by force .
so why would you use System.exit(1) if you want some code to execute after the exit
simply apply some condition within yout try block to exit try block , which leads to finnaly block in every case

Categories