As an addition to my current application, I need to create a separate thread which will periodically do some processing
I've create a new class to do all this, and this class will be loaded on startup of my application.
This is what I have so far :
public class PeriodicChecker extends Thread
{
static
{
Thread t = new Thread(new PeriodicChecker());
while(true)
{
t.run();
try
{
Thread.sleep(5000l);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
/**
* Private constructor to prevent instantiation
*/
private PeriodicChecker()
{
}
#Override
public void run()
{
System.out.println("Thread is doing something");
// Actual business logic here, that is repeated
}
}
I want to make constructor private to prevent other people from attempting to instantiate this class accidentally. How can I achieve this?
Also, is there anything bad about my implementation of such requirements? I'm only creating one thread which will run then sleep, have I missed anything obvious? I haven't worked with threads before
Java offers ScheduledExecutorService to schedule and run periodic tasks or tasks with delay. It should provide all the features you need. Timer is another class that offers similar functionalities, but I would recommend the ScheduledExecutorService over Timer for its flexibility of configuration and better error management.
You have some conceptual erros in your code... for example:
You should call start() and not run(), because you are running the method sequentially and not simultaneously.
You can call start() only once, not once in each loop iteration. After that, the thread is in state TERMINATED, you should create a new thread to run it again
You should not create the thread in the static block, it is a bad practice, and maybe the Thread is running before you want it to run.
You should read some examples about thread, it is a little difficult to unserstand at the beginning, and you can have undesired effects very easily.
Here is a little example, that may do something similar to that you want:
public class PeriodicChecker extends Thread
{
#Override
public void run()
{
while(true) {
System.out.println("Thread is doing something");
Thread.sleep(5000);
}
}
}
public OtherClass {
public static void main(String args[]) {
Thread t = new PeriodicChecker();
t.start();
}
}
If you want that none can create a new Thread, you could create a singleton, so you will be sure that none is creating more threads.
I'd recommend you to consider Timer class - it provides functionality for periodic tasks execution.
Also you may take a look at "Timer & TimerTask versus Thread + sleep in Java" question discussion - there you can find some arguments and examples.
First of all to answer your specific question, you have already achieved your objective. You have declared your constructor to be private meaning no external class can call it like new PeriodicChecker().
Looking at your code however, there are a number of other problems:
Firstly, you are creating an instance of your class within its own static constructor. The purpose of a static constructor is to initialise any static state that your class may have, which instances of your class may then depend on. By creating an instance of the class within the static constructor, all of these guarantees go out the window.
Secondly, I don't think your thread is going to behave in the way you expect it to behave, primarily because you don't actually start another thread :). If you intend to start a new thread, you need to call the start() method on that thread object. Calling run() as you do does not actually create a new thread, but simply runs the run() method in the current thread.
Nowadays when you want to create a new thread to do something, the reccomended way of achieving this is to not extend Thread, but instead implement the Runnable interface. This allows you to decouple the mechanism of the thread, from the behaviour you intend to run.
Based on your requirements, I would suggest doing away with a top-level class like this, and instead create either a private inner class within your application start-up code, or even go for an anonymous inner class:
public class Main {
public static void main(String[] args) {
new Thread(new Runnable() {
#Override
public void run() {
while(true) {
System.out.println("Thread is doing something");
Thread.sleep(5000);
}
}
}).start();
}
}
It is almost never right to extend Thread. If you ever find yourself doing this, step back, take a look and ask yourself if you really need to change the way the Thread class works.
Almost all occurances where I see extends Thread the job would be better done implementing the Runnable interface or using some form of Timer.
Related
I am pretty new to using multithreading, but I want to invoke a method asynchronously (in a separate Thread) rather than invoking it synchronously. The basic idea is that I'm creating a socket server with an object in memory, so for each client I will have to run something like object.getStuff() asynchronously.
The two constructs I found were:
having the class implement Runnable and threading this and
declaring a runnable class within a method.
Additionally this method needs a return value- will it be necessary to use Executor and Callable to achieve this? Could someone point me in the right direction for implementing this?
I have tried implement option 2, but this doesn't appear to be processing concurrently:
public class Test {
private ExecutorService exec = Executors.newFixedThreadPool(10);
public Thing getStuff(){
class Getter implements Callable<Thing>{
public Thing call(){
//do collection stuff
return Thing;
}
}
Callable<Thing> callable = new Getter();
Future<Thing> future = exec.submit(callable);
return future.get();
}
}
I am instantiating a single test object for the server and calling getStuff() for each client connection.
Threading Tutorial
The Java tutorial on concurrency has a good section on this. It's at https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html. Essentially, you can either implement Runnable or Callable, or inherit from Thread.
Subclassing Thread
You can write a class, including an anonymous inner class, that extends Thread. Instantiate it, then invoke the start() method.
public class MyThread extends Thread {
public void run() {
System.out.println("This is a thread");
}
public static void main(String[] args) {
MyThread m = new MyThread();
m.start();
}
}
Implementing Runnable
You can write a class that implements Runnable, then wrap an instance in a Thread and invoke start(). Very much like the previous.
public class MyRunnable implements Runnable {
public void run() {
System.out.println("This is a thread");
}
public static void main(String[] args) {
MyRunnable r = new MyRunnable();
(new Thread(r)).start();
}
}
Return Value
Runnable doesn't allow for return values. If you need that, you need to implement Callable instead. Callable looks a lot like Runnable, except you override the call() method instead of the run() method, and you need to give it to an ExecutorService.
public class MyCallable implements Callable<Integer> {
public Integer call() {
System.out.println("A thread using Callable<Integer>");
return 42;
}
public static void main(String[] args) {
MyCallable c = new MyCallable();
Future<Integer> f = Executors.newSingleThreadExecutor().submit(c));
System.out.println("The thread returned: " +
f.get());
}
}
The two constructs I found were 1) having the class implement Runnable and threading 'this' and 2) declaring a runnable class within a method.
Option (2) probably is better. Most programs would be improved if they had more classes, not fewer. Each named entity in a program—each package, class, method, whatever—should have just one responsibility. In your option (1), you are asking the class to do two things.
For your option (2), you don't actually have to declare a whole class. You can either use an anonymous inner class, or if you can go with Java8 all the way, you can use a lambda expression. Google for either one to learn more.
Additionally this method needs a return value.
The classic way, is for the Runnable object to return the value through one of its own fields before the thread terminates. Then the parent thread, can examine the object and get the return value afterward.
Will it be necessary to use Executor and Callable to achieve this?
Necessary? A lot of people think that ExecutorService is a Good Thing.
Sounds like you are creating a server that serves multiple clients. Do these clients continually connect and disconnect? The advantage of using a thread pool (i.e., ThreadPoolExecutor) is that it saves your program from continually creating and destroying threads (e.g., every time a client connects/disconnects). Creating and destroying threads is expensive. If you have a lot of clients connecting and disconnecting, then using a thread pool could make a big difference in the performance of your server.
Creating and managing threads by yourself is generally bad approach.
As you already pointed - use Executors utility class to create executor and submit Callables to it.
public class RunWResult implements Runable{
private volatile ResultType var;
//the thread method
public void run(){
...
//generate a result and save it to var
var = someResult();
//notify waiting threads that a result has been generated
synchronized(this){
notify();
}
}
public ResultType runWithResult(){
//run the thread generating a result
Thread t = new Thread(this);
t.start();
//wait for t to create a result
try{
wait();
}catch(InterruptedException e){}
//return the result
return var;
}
}
Just a quick question look at the code below, is there any reason why wouldn't do this or is it fine?
public class MyClass implements Runnable, MyClassInterface {
Thread threader;
void start() {
threader = new Thread(this);
threader.start();
}
#Override
public void run() {
Thread current = Thread.getCurrentThread();
while (threader = current) {
..
}
}
}
The original logic was not to expose that fact it runs in a separate thread to the caller
who creates a "MyClass" but then there are doubts if that is a good thing or bad.
Can anyone see any good reason not to do it or is it acceptable. It can be expected that MyClass.start() maybe called a few times.
EDIT: Updated the code to show it is implementing Runnable and one other interface, the interface is used by client code, the actual implementation may run in a separate thread, same thread or any other way. The idea was to abstract that away from the client, as the client is simply an object that "MyClass" will notify and is not aware (currently) of the Runnable interface it implements.
Perhaps that abstraction is not needed and client should have more control?
EDIT: The start() was simply to tell the object it is ready to start receiving notifications rather than start a thread.
Have a look at this: http://docs.oracle.com/javase/8/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html
In my opinion, it is a bad design, because you are breaking encapsulation by implementing an interface (Runnable) and by providing a public method (run) that are of no use of the consumer of the class.
You can start a thread from the start method without inhering from Runnable:
public class MyClass {
private Thread thread;
public void start() {
thread = new Thread(this::doWork); // Java 8 method reference
thread.start();
}
private void doWork() {
// ...
}
}
If you can't use method references from Java 8, replace this::doWork with:
new Runnable() { public void run() { doWork(); } }
I want to invoke different methods of class at same time.
I am creating 2 classes: Main- this instantiate object of Function and Function; this extends thread and has 2 methods.
Main.java
package ok;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Welcome to Threading");
Function f1 = new Function();
f1.start();
f1.calling();
f1.calling2();
}
}
Function.java
package ok;
public class Function extends Thread {
public void run() {
// TODO Auto-generated method stub
System.out.println("Run");
for(int y=140;y<170;y++){
System.out.println(y);
}
}
synchronized void calling(){
System.out.println("Let the game begin");
for(int y=40;y<70;y++) {
System.out.println(y);
}
}
synchronized void calling2(){
System.out.println("Let the game begin for me");
for(int y=0;y<40;y++) {
System.out.println(y);
}
}
}
How can I make the methods calling() and calling2() work at the same time?
If I start a thread it goes to run() call and doesn't have any return type. In my program, I need to have return value as a HashMap.
Do I need to create two classes which extends Threads and write logic of calling(), calling2() in run of those two classes?
Please suggest.
Your calling and calling2 methods are synchronized. The very essence of synchronized keyword is to prevent methods from executing concurrently. So in order to invoke both calling and calling2 in parallel you need to drop the synchronized keyword, at least from the method level.
Then, to invoke two methods at the same time, one Thread object is enough - one invocation can be executed in new thread, the other in the "current" thread, like this:
Thread thread = new MyThread();
thread.start(); // body of run() invoked in a new thread
thread.run(); // body of run() invoked in this thread, concurrently
It's better practice to produce separate Runnable objects for such use-cases, though. This has several advantages over the aformentioned approach:
it's more flexible - as the action is decoupled from the execution and encapsulated in a separate object, it becomes more like "data". If you ever feel the need to change computation strategy - e.g. use thread pool - it's trivial to do so with Runnable tasks. Not so with Thread extensions.
it's conceptually more sound, as subclassing a Thread suggests specializing its behaviour, while Runnables are more like "task containers" - favor composition over inheritance.
it's symmetric - no computation is treated differently, it's trivial to change e.g. which one executes where
Last, you seem to want to return something from your methods. For this, you might use a Future - a java concurrency utility class, representing asynchronous computation. In addition to Runnable advantages, it can return a value and offers features like cancellation and state querying.
You have to have the calls for running the methods inside your run() method.
Then you can just call the start() method and both methods will run. But that does not really solve the problem. What you need to do is create two threads and have each of them run their respective threads.
If I start a thread in a static block. Will the jvm wait for the thread to finish before it loads the class?
static {
System.out.println("static block");
DataRetrievalThread t = new DataRetrievalThread();
t.run();
}
The reason I'm trying this is because
I want to retrieve data from a server and it's taking way too long to get it. So to persist the data I want to retrieve it and store it in a file so that when the client asks for it - it does not need to make the call to the server to get the information.
If I start a thread in a static block. Will the jvm wait for the thread to finish before it loads the class?
Uh. Yes and no and NO.
First off, your code is not forking a thread. So as it is written it will hold up the class construction although technically the class is "loaded" before the static section runs. That's because you are executing the run() method directly in the current main thread. If you want to fork the thread then you should call t.start();.
If you actually fork the thread with t.start() then no, the thread will run in the background and will not hold up the class initialization.
You really should not be doing something like this. It's a tremendously bad pattern. If you explain what you are trying to accomplish, we should be able to really help.
If you are trying to pre-load data into your program then you should just run the load part early on in main() and don't park it in a static initializer in a class. But if you are running it in the main thread, holding up the program, I don't see why this is any faster then making the request on demand.
One thing to consider is to fork (with t.start()) a background thread to load the data and then have a class which holds the data. If the thread finishes in time then it will have pre-loaded the data. When the program needs the data, it should call the class to get it. If the thread hasn't finished it could do a countDownLatch.await(). When the thread finishes the download it could do countDownLatch.countDown(). So you will get some parallelism.
Something like:
public class DataLoader {
private volatile Stuff data;
private final CountDownLatch latch = new CountDownLatch(1);
// start the thread, called early in main()
public void init() {
// you pass in this so it can call setData
DataRetrievalThread t = new DataRetrievalThread(this);
t.start();
}
// called from the DataRetrievalThread
public void setData(Stuff data) {
this.data = data;
latch.countDown();
}
public Stuff getData() {
if (data == null) {
latch.await();
}
return data;
}
}
With run() you execute the method in the current thread, so after that the class will finish loading. You need to call start() to run the method in a new thread.
In a swing application, I would like to re-utilize a spawned thread instead of creating a new one to serve requests. This is because the requests would be coming in short intervals of time and the cost of creating a new thread for every request could be high.
I am thinking of using the interrupt() and sleep() methods to do this as below and would like to know any potential performance problems with the code:
public class MyUtils {
private static TabSwitcherThread tabSwitcherThread = null;
public static void handleStateChange(){
if(tabSwitcherThread == null || !tabSwitcherThread.isAlive()){
tabSwitcherThread = new TabSwitcherThread();
tabSwitcherThread.start();
}
else
tabSwitcherThread.interrupt();
}
private static class TabSwitcherThread extends Thread{
#Override
public void run() {
try {
//Serve request code
//Processing complete, sleep till next request is received (will be interrupted)
Thread.sleep(60000);
} catch (InterruptedException e) {
//Interrupted execute request
run();
}
//No request received till sleep completed so let the thread die
}
}
}
Thanks
I wouldn't use sleep() and interrupt() - I'd use wait() and notify() if I absolutely had to.
However, is there any real need to do this instead of using a ThreadPoolExecutor which can handle the thread reuse for you? Or perhaps use a BlockingQueue in a producer/consumer fashion?
Java already provides enough higher-level building blocks for this that you shouldn't need to go down to this level yourself.
I think what you're looking for is a ThreadPool. Java 5 and above comes with ThreadPoolExecutor. I would suggest you use what is provided with Java instead of writing your own, so you can save yourself a lot of time and hairs.
Of course, if you absolutely has to do it the way you described (hey, sometimes business requirement make our life hard), then use wait() and notify() as Jon suggested. I would not use sleep() in this case because you have to specified timeout, and you never know when the next request will come in. Having a thread that keep waking up then go back to sleep seems a bit wasteful of CPU cycle for me.
Here is a nice tutorial about the ThreadPoolExecutor.
EDIT:
Here is some code example:
public class MyUtils {
private static UIUpdater worker = null;
private static ExecutorService exeSrv = Executors.newFixedThreadPool(1);
public static void handleStateChange(){
if(tabSwitcherThread == null || !tabSwitcherThread.isAlive()){
worker = new UIUpdater();
}
//this call does not block
exeSrv.submit(worker, new Object());
}
private static class UIUpdater implements Runnable{
#Override
public void run() {
//do server request and update ui.
}
}
}