java threads common questions [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have some questions about java threads:
if I have a class that runs a number of threads when one thread reaches to exit(1) command line will it exit the thread or the whole application including the other threads?
2.how can I make one thread notify all other threads that run from the same class to stop?
3.does using synchronized make only one thread ,regardless his source in the code, to do this part of code?
4.if I am running a thread in java using run() if I call a method from inside the run() does this still running as a thread or it is not allowed?

1) Only if thread are daemons, application will not wait to close even if they are running.
Example: comment or not the setDaemon(true)
public class Test {
public static void main(final String[] args) {
new Launcher(parent).start();
}
public static class Launcher extends Thread {
public Launcher(final String name) {
this.setName(name);
}
#Override
public void run() {
System.err.println(getName() + is starting);
for (int i = 0; i < 10; i++) {
new Waiter(child + i).start();
}
try {
Thread.sleep(1000);
System.err.println(getName() + is no more sleeping);
} catch (final InterruptedException e) {
e.printStackTrace();
}
System.err.println(getName() + is stopping);
}
}
public static class Waiter extends Thread {
public Waiter(final String name) {
super(name);
super.setDaemon(true);
}
#Override
public void run() {
System.err.println(getName() + is starting);
try {
Thread.sleep(12000);
System.err.println(getName() + is no more sleeping);
} catch (final InterruptedException e) {
e.printStackTrace();
}
}
}
}
2) To force the stop, you can use different approach, different patterns. Sorry to not have THE solution. You can take a look at : http://docs.oracle.com/javase/7/docs/api/java/lang/ThreadGroup.html
3) Yeah, it's the goal of synchronized.
4) It depends what you do but basically, calling a method do not launch another thread, except if the methods does it.

if I have a class that runs a number of threads when one thread reaches to exit(1) command line will it exit the thread or the whole application including the other threads?
A call to System.exit(1) will terminate the calling thread and all other threads. It is the most brutal way of ending a Java program, namely completely shutting down the JVM, and should rarely be used at all.
how can I make one thread notify all other threads that run from the same class to stop?
Not at all. If you have references to the other Thread objects, you can call Thread#interrupt(), but whether or not the other threads check their interrupted status or reach a place where they may throw an InterruptedException is left to them.
does using synchronized make only one thread ,regardless his source in the code, to do this part of code?
Intuitively yes. However, when there is a wait() in this block, then the corresponding lock (that is, the object that was synchronized on) will be released and can be acquired by other threads.
if I am running a thread in java using run() if I call a method from inside the run() does this still running as a thread or it is not allowed?
When a thread calls a method, then the same thread also executes this method (silently wondering how else it should be...)

Related

Can a Thread interrupt itsself? [duplicate]

This question already has answers here:
Interrupting a thread from itself
(4 answers)
Closed 2 years ago.
I wanted to ask if it is possible for a thread to end itself. I have a method in an instance of a thread that checks if an int Overflows but its not the run() method. I want to stop the thread if the internalSteps reach Integer.MAX_VALUE / numberOfAllThreads
private void addInternalStep() {
++internalSteps;
if( internalSteps == (Integer.MAX_VALUE / numberOfAllThreads) ) {
System.out.println("Thread stopped. In danger of overflow.");
this.interrupt(); // Not stopping the thread
}
}
#Override
public void run() {
while( !isInterrupted() ) {
if(Math.pow(Math.random(), 2) + Math.pow(Math.random(), 2) < 1) {
hits = hits.add(BigDecimal.ONE);
}
counter = counter.add(BigDecimal.ONE);
addInternalStep();
}
}
Why isnt this.interrupt() working ? And how do I interrupt the thread in the instance of itsself ?
Calling interrupt only sets a flag, it doesn’t have any other effect.
A thread can call interrupt on itself. This can happen when a thread catches an InterruptedException and wants to restore the flag that got cleared when the exception was thrown.
This usually looks something like:
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
Thread.currentThread().interrupt():
}
But this special case is about the only time it makes sense.
Using the currentThread method makes sure the interrupt call acts on the currently executing thread regardless of how the code is executed.

Stop a method in java

I have made a method to send an e-mail, and I wanted to try if it was possible to call a method inside the method itself with a timer, to do like a scheduler
public void createExcel(){
int year = Calendar.getInstance().get(Calendar.YEAR);
int num_week = data.getCurrentWeek()-1;
ArrayList<DHDemande> ListeDemandes = d.getDemandesForPaie(num_week, year);
try {
data.createFile(ListeDemandes);
Thread.sleep(20000);
createExcel();
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
But now the method doesn't stop (it was obvious) but even if I refresh Apache and if I change the method. How can I stop it ? because I receive an email every 20 second now
The thing with Treads is that there is now save way to tell it to just stop without memory leaks. You can use thread.stop(), this will kill the thread but it may cause memory problems if your objects are too big.
Quote from java doc:
stop() Deprecated. This method is inherently unsafe. Stopping a
thread with Thread.stop causes it to unlock all of the monitors that
it has locked (as a natural consequence of the unchecked ThreadDeath
exception propagating up the stack). If any of the objects previously
protected by these monitors were in an inconsistent state, the damaged
objects become visible to other threads, potentially resulting in
arbitrary behavior. Many uses of stop should be replaced by code that
simply modifies some variable to indicate that the target thread
should stop running. The target thread should check this variable
regularly, and return from its run method in an orderly fashion if the
variable indicates that it is to stop running. If the target thread
waits for long periods (on a condition variable, for example), the
interrupt method should be used to interrupt the wait. For more
information, see Why are Thread.stop, Thread.suspend and Thread.resume
Deprecated?.
Explore the Thread api and see if you can find anything else that suites your needs.
As Borislav mentioned, stop() is incorrect here, you need to call and handle interrupt().
class Test
{
public static Thread helloWorldLater()
{
Thread t = new Thread(new Runnable(){
#Override public void run()
{
try {
Thread.sleep(200);
System.out.println("Hello World");
}
catch(InterruptedException ex)
{
// clean up here
return;
}
}
});
t.start();
return t;
}
public static void main(String[] args) throws InterruptedException
{
Thread t = helloWorldLater();
Thread.sleep(100);
t.interrupt();
// no "Hello World" to be seen
}
}
Alternatively, depending on your Java version, you can also use the more modern concurrency Java APIs.
Besides Borislavs and Konrads legitimate comments on thread.stop(), you are calling the createExcel() method recursively (after Thread.sleep(20000)), so obviously your method will run forever. If you remove that call it should work like you expect it.

Thread interference when calling synchronized queue methods

Running my program, which is multithreaded, seems to lead to thread interference even though I used the keyword synchronized for the methods that have an effect on the part where my problem lies.
I have a static nested class Station which has the following methods in it:
public synchronized boolean addQueuer(String ID)
{
if (!buffer.isFull())
{
buffer.enqueue(ID);
return true;
}
return false;
}
private synchronized void removeQueuer()
{
buffer.dequeue();
}
Buffer is a simple queue with wrapping.
In two different threads, I call these methods. In the encapsulator, the main method has the following lines of code:
while (true)
{
stations[0].addQueuer("M");
Thread.sleep(FREQ_TIMER);
}
Where stations is an array of Station containg a single station in my test
And in Station I have the following run() function for implementation of Runnable (I start a thread by creating an instance of this class, then call start() for this thread):
public void run()
{
try
{
Thread.sleep(ESTIMATED_SERVICE_TIME);
while (!buffer.isEmpty())
{
removeQueuer();
}
if (isOpen)
run();
} catch (InterruptedException interruptException)
{
threadMessage("This station was interrupted.");
}
}
What is going wrong:
I have adjusted the CONSTANTS so that the buffer should fill up quicker than it gets emptied. However, when I run my program the buffer might start at 7, go down to 6 at next run in the next loop, then it will stay at 6 forever.
First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object. - Java Tutorials
Why is it not enough to put synchronize? If any additional context/information is required, please comment and I'll try abide.
Edit: Added the entire code.

Java - Running a thread twice [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
From another post:
If a Thread needs to be run more than once, then one should make an
new instance of the Thread and call start on it.
How is this done?
I would use another layer of abstraction. Use an ExecutorService.
Here is a simple example:
public static void main(String args[]) throws InterruptedException {
final ExecutorService service = Executors.newCachedThreadPool();
final class MyTask implements Runnable {
#Override
public void run() {
System.out.println("Running my task.");
}
};
for (int i = 0; i < 10; ++i) {
service.submit(new MyTask());
}
service.shutdown();
service.awaitTermination(1, TimeUnit.DAYS);
}
Just dump your task into the service as many times as you want.
The ExecutorService is a thread pool - it has a number of Threads that take tasks as they come. This removes the overhead of spawning new Threads because it caches them.
Basically, a thread cannot be restarted.
So if you want a reusable "thread", you are really talking about a Runnable. You might do something like this:
Runnable myTask = new Runnable() {
public void run() {
// Do some task
}
}
Thread t1 = new Thread(myTask);
t1.start();
t1.join();
Thread t2 = new Thread(myTask);
t2.start();
(This is purely for illustration purposes only! It is much better to run your "runnables" using a more sophisticated mechanism, such as provided by one of the ExecutorService classes, which is going to manage the actual threads in a way that avoids them terminating.)
A java Thread cannot be run twice. Once it has been started and finished its work, it cannot be started again (calling method start will fail). So you'll have to create a new instance of Thread (using the same Runnable) and start it.

Java thread join 3

The program creates thread t0 which spawns thread t1 and subsequently threads t2 and t3 are created.After the execution of thread t3and the application never returns to the other threads spawned earlier(t0,t1,t2) and they are left stuck.
Why are the threads t0, t1, and t2 suspended?
public class Cult extends Thread
{
private String[] names = {"t1", "t2", "t3"};
static int count = 0;
public void run()
{
for(int i = 0; i < 100; i++)
{
if(i == 5 && count < 3)
{
Thread t = new Cult(names[count++]);
t.start();
try{
Thread.currentThread().join();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
System.out.print(Thread.currentThread().getName() + " ");
}
}
public static void main(String[] a`)
{
new Cult("t0").start();
}
}
The most important point you missed:
Thread.currentThread().join();
Method join in source code uses isAlive method.
public final synchronized void join(long millis)
...
if (millis == 0) {
while (isAlive()) {
wait(0);
}
...
}
It means that Thread.currentThread().join() will return only when Thread.currentThread() is dead.
But in your case it's impossible because of your running code in Thread.currentThread() has itself
this peace of code Thread.currentThread().join(). That's why after Thread 3 completion your program should hang and nothing happens thereafter.
Why are the threads t0, t1, and t2 suspended? The execution of thread t3 completes.
t3 completes because it is not trying to fork a 4th thread and therefore is not trying to join() with it's own thread. The following line will never return so t0, t1, and t2 all stop there and wait forever:
Thread.currentThread().join();
This is asking the current thread to wait for itself to finish which doesn't work. I suspect that you meant to say t.join(); which is waiting for the thread that was just forked to finish.
Here are some other thoughts about your code in no apparent order:
You should consider implements Runnable instead of extends Thread. See here: "implements Runnable" vs. "extends Thread"
You are using the shared static variable count in multiple threads without any protection of locking. The best solution is to use an AtomicInteger instead of a int. You probably don't have a problem here because each thread is modifying count and then forking another thread but if you tried to fork 2 threads, this would be a real problem because of data race conditions.
I'm not sure why you are only spawning another thread if(i == 5 && count < 3). i is only going to be 5 once in that loop. Is that really what you intended?
String[] names = {"t1", "t2", "t3"}; fields are recommended to be declared at the top of classes. Otherwise they get buried in the code and get lost.
In main you start a Cult thread and then the main thread finishes. This is unnecessary and you can just call cult.run(); in main instead and use the main thread.
Cult(String s) { super(s); } there is no point in having a constructor that calls the super constructor with the same arguments. This can be removed.
This is debatable but I tend to put main method at the top of the class and not bury it since it is the "entrance" method. Same thing with constructors. Those should be above the run() method.
catch(Exception e) {} is a really bad pattern. At the very least you should do a e.printStackTrace(); or log it somehow. Catching and just dropping exceptions hides a lot of problems. Also, catching Exception should be changed to catch(InterruptedException e). You want to restrict your catch blocks just the exceptions thrown by the block otherwise this may again hide problems in the future if you copy and paste that block somewhere.
More a good practice but never use constants like 3 that have to match another data item. In this case it would be better to use names.length which is 3. THis means that you don't need to change 2 places in the code if you want to increase the number of threads. You could also have the name be "t" + count and get rid of the names array altogether.

Categories

Resources