Multi threading in Jboss - java

I want to see how Jboss creates/assign different threads from Thread pool once it finds previous thread busy.For that i tried to write down a code I hope making a thread sleep will make it busy and Jboss will create a new one. But it didnt work.
I want my Test0 class to create 5 threads to execute run method of Test1 whenever it finds Test1 thread is busy in doing something.
public class Test1 extends Thread{
public Test1(){
System.out.println("T1 Constructor");
}
#Override
public void run() {
System.out.println("run from t1 "+ Thread.currentThread().getName());
try {
Thread.currentThread().sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
And I have Test0 class which will execute when jboss will start as follows
#Singleton
#Startup
public class Test0 {
private Test1 t1;
public Test0(){
}
#PostConstruct
public void starts(){
for (int i=0;i<5;i++){
t1=new Test1();
t1.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Now in Test0 class I am manully creating 5 threads . How should i format the code to have Jboss create Thread from Thread pool?
Will it make any difference if i call t1.run() instead of t1.start() while running on servers? Because i know t1.run will not create a new thread but so this still holds same in case of servers as well?

If i understand your question correctly you want to know when a new thread is used from Jboss thread pool. How are you checking if JBoss has spawned a new thread? Is it you looking at the Jboss log. Jboss will start a new thread only if a new client request is sent to Jboss server while existing thread is already busy executing prev request. Fire multiple client request to Jboss server to see multiple threads processing your code at a given point of time.

Related

How to know when a thread stops or is stopped?

I have the next code:
Executor exe = Executors.newFixedThreadPool(20);
while (true) {
try {
exe.execute(new DispatcherThread(serverSocket.accept()));
continue;
} catch (SocketException sExcp) {
System.exit(-1);
} catch (Exception excp) {
System.exit(-1);
}
}
For each DispatcherThread I create a connection to the database (it means I have 20 connections), what I need to know is how I can close the connection to the database when the thread is stopped or it stops or finishes its flow.
You cannot directly know when the thread is stopped, the closest thing you have is Thread#isAlive method but it may return false when the run method in the thread has finished but the thread may not be stopped since the JVM cannot guarantee it. But if your DispatcherThread class implements Runnable interface then you can write the clean up at the bottom of the run method.
Skeleton code:
class DispatcherThread implements Runnable {
#Override
public void run() {
try {
//open database connection an such...
//...
//handle the work here...
} catch (...) {
//ALWAYS handle the exceptions
} finally {
//cleanup tasks like close database connection
}
}
}
By the way, Thread suffix is not a good name for a class that technically is not a thread (because it doesn't extend from Thread). Instead, give a proper name according to what should do.
You could close the thread-specific connection at the end of your run() method.
A finally block would ensure that it happened however the run() method exited.
class DispatcherThread extends Runnable {
public void run() {
...
try {
...
}
finally {
// Close the connection
}
}

Testing concurrency in Java

According to book Java Concurrency in Practice at Listing 12.3 we could test a concurrent code using the following sample code:
void testTakeBlocksWhenEmpty() {
final BoundedBuffer<Integer> bb = new BoundedBuffer<Integer>(10);
Thread taker = new Thread() {
public void run() {
try {
int unused = bb.take();
fail(); // if we get here, it’s an error
} catch (InterruptedException success) { }
}
};
try {
taker.start();
Thread.sleep(LOCKUP_DETECT_TIMEOUT);
taker.interrupt();
taker.join(LOCKUP_DETECT_TIMEOUT);
assertFalse(taker.isAlive());
} catch (Exception unexpected) {
fail();
}
}
Let's say that the following steps are executed:
taker thread started.
bb.take() returned successfully and we are just a little bit before the fail() method run.
It is called the interrupt() method.
We are at the catch block of the taker thread.
So, we are at the catch block at the moment but actually the test method failed. It is failed and we are never informed.
Is this right? If yes how could we fix this?
take is supposed to block on an empty queue. So the expected sequence of events is:
taker.start(); => start the thread
Thread.sleep(LOCKUP_DETECT_TIMEOUT); wait to make sure the thread is started and take has been called. The actual value of the constant is hard to estimate, but anything above a few hundreds of millis should be enough - alternatively you could use a CountDownLatch to know when the taker thread is started
in taker thread: bb.take(); => is supposed to block - if it doesn't fail() is called and the test fails
in main thread: taker.interrupt(); => the take() method is supposed to exit with InterruptedException
in main thread: taker.join(); => wait for some time to allow the taker thread to finish
in main thread: assertFalse(taker.isAlive()); => confirm that the taker thread has exited and is not blocked in the take method any more
Version with a latch (it assumes that if the thread is interrupted before take is called, take will exit with an InterruptedException - if not then you have no other way but to add some random sleep before calling started.await()):
void testTakeBlocksWhenEmpty() {
final CountDownLatch started = new CountDownLatch(1);
final CountDownLatch ended = new CountDownLatch(1);
final BoundedBuffer<Integer> bb = new BoundedBuffer<Integer>(10);
Thread taker = new Thread() {
public void run() {
try {
started.countDown();
int unused = bb.take();
fail(); // if we get here, it’s an error
} catch (InterruptedException success) { }
ended.countDown();
}
};
try {
taker.start();
started.await();
taker.interrupt();
assertTrue(ended.await());
} catch (Exception unexpected) {
fail();
}
}
You should add a timeout to your test method or to the latch (long enough to not interfere if the test passes, for example 5 seconds). That will avoid blocking your whole test suite.

Confusion on Thread setDeaemon in java

According to java when setDaemon is set to true
it does not prevent the JVM from
exiting when the program finishes but
the thread is still running. An
example for a daemon thread is the
garbage collection.
From the following code sample , the thread created by main thread stops executing when setDaemon is set to true, actually it should keep on running . when setDaemon is set false the child thread print value of i even though main thread exited.
kindly clarify my doubt.
public class DeamonSample implements Runnable
{
public void run()
{
try
{
System.out.println("T1 started...");
for (int i=0;i<1000;i++)
{
TimeUnit.SECONDS.sleep(1);
System.out.print(i+" ");
}
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
System.out.println("T1 ended...");
}
}
/**
* #param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
System.out.println("Main Started...");
System.out.println("Main Thread Type="+Thread.currentThread().isDaemon());
DeamonSample deamonSample=new DeamonSample();
Thread t1=new Thread(deamonSample);
t1.setDaemon(true);
t1.start();
System.out.println("T1 Type="+t1.isDaemon());
System.out.println("Main Thread Type="+Thread.currentThread().isDaemon());
System.out.println("Main ended...");
}
}
By default threads are not daemon threads. If you get to the end of your main with any thread that's not a daemon then the process will keep running. By calling setDaemon(true) you're telling the JVM that your thread shouldn't block shutdown at the end of main.
The DeamonSample instance is assuredly not stopped when t1.setDaemon(true); is executed; the nondeterminism that you see comes from the prints. Characters are written to thread-local buffers before they are merged into a single stream.
Here's a bit of code to illustrate. Two threads take turns incrementing a counter and printing its state, but the numbers you see may be very much out of order.
import java.util.concurrent.atomic.AtomicInteger;
public class FunnyPrinter extends Thread {
static AtomicInteger counter = new AtomicInteger(0);
int parity;
public FunnyPrinter(int parity) {
super();
this.parity = parity;
}
public void run() {
for (;;)
if (counter.intValue() % 2 == parity)
System.out.println(counter.incrementAndGet());
}
public static void main(String[] args) {
FunnyPrinter t1 = new FunnyPrinter(0), t2 = new FunnyPrinter(1);
t1.start(); t2.start();
}
}
If you need determinism, synchronize on System.out and flush it before the end of the block.
From the following code sample , the thread created by main thread stops executing when setDaemon is set to true
This will not happen. Check your output again. Your output will contain the following lines:
Main Started...
Main Thread Type=false
T1 Type=true
Main Thread Type=false
Main ended...
..actually it should keep on running .
Being a daemon thread, it wont. Since all non-daemon threads (main) have finished, the jvm will exit.
when setDaemon is set false the child thread print value of i even though main thread exited. kindly clarify my doubt.
Correct
The main-thread terminates, before your daemon-thread can print out all your numbers...
if your new thread isDaemon = true, try this line after starting the thread ():
...
Thread t1=new Thread(deamonSample);
try{
t1.join();
}catch(InterruptedException ie){
ie.printStackTrace();
}
...
you will see, the daemon-thread will come to an end... (at least, that wouldn´t be multithreading anymore, but that example is for clarifying purpose only)

Creating threads in Java

I am a newbie to Java and wondering whether I can create threads in following way.
Desired Java Code :
Class MyClass {
Myclass(){
Statement1;//Create a thread1 to call a function
Statement2;//Create a thread2 to call a function
Statement3;//Create a thread3 to call a function
}
}
Is it possible to create threads like the above code?
The Java Concurrency tutorial includes a page on defining and starting threads. You might want to read through it along with the other pages in the concurrency tutorial.
Echoing GregInYEG, you should check out the tutorial, but the simple explanation is as follows:
You need to create an object class which either extends Thread or implements Runnable. In this class, create (actually, overload) a void method called "run." Inside this method is where you put the code that you would like this thread to execute once it is forked. It could simply be a call to another function if you wish. Then, when you would like to spawn a thread of this type, create one of these objects and call the "start" (not run!) method of this object. eg newThread.start();
It's important to call "start" and not "run" because a run call will simply call the method just like any other, without forking a new thread.
Still, be sure to read up in further detail and there are many more important aspects of concurrency, especially that of locking shared resources.
Yes, it is possible. You want to put your logic for each statement inside a Runnable implementation, and then pass each constructed Runnable to a new instance of Thread. Check out those 2 classes and it should become fairly obvious what you need to do.
I agree with all written here. The thread can be created in a two ways.
To extend thread class . YouTube Tutorial
To implement Runnable Interface YouTube Tutorial
Example for the first method
public class MyThread extends Thread {
public void run()
{
int iterations = 4;
for(int i=0;i<iterations;i++)
{
System.out.println("Created Thread is running " + Thread.currentThread().getId() + " Printing " + i) ;
try {
sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.err.println(e);
}
}
System.out.println("End of program");
}
}
To create a thread
MyThread myThread = new MyThread();
myThread.start();
Second method to implement runnable interface
public class RunnableThread implements Runnable {
#Override
public void run() {
int iterations = 4;
for(int i=0;i<iterations;i++)
{
System.out.println("Runnable Thread is running " + Thread.currentThread().getId() + " Printing " + i) ;
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.err.println(e);
}
}
System.out.println("End of program");
}
}
To create a thread
new Thread(new RunnableThread()).start();
So I think you can use both of these methods in you case statements

How to lock a java method to protect multiple invocations

I have an application that every 15 minutes or so does a replication from a remote database. It just keeps the two repositories in sync. Once this replication is going it is not possible to do it again. I have setup the following structure but I'm not sure if it is the correct approach.
public class ReplicatorRunner {
private static Lock lock = new ReentrantLock();
public replicate() {
if (lock.tryLock()) {
try {
// long running process
} catch (Exception e) {
} finally {
lock.unlock();
}
} else {
throw new IllegalStateException("already replicating");
}
}
}
public class ReplicatorRunnerInvocator {
public void someMethod() {
try {
ReplicatorRunner replicator = new ReplicatorRunner();
replicator.replicate();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
}
The ReplicatorRunner is the class owning the method replicate which can only be run one at a time.
Edit.
I need the next call to fail (not block) if the method is already running on any instance.
This looks good. ReentrantLock.tryLock() will only give the lock to one thread, so synchronized is not necessary. It also prevents the blocking inherent in synchronization that you say is a requirement. ReentrantLock is Serializable, so should work across your cluster.
Go for it.
Change public replicate() to public synchronized replicate()
That way replicate will only ever allow access to one thread at a time. You'll also be able to delete the ReentrantLock and all associated code.
I ended up using the following:
public class ReplicatorRunner {
private static Semaphore lock = new Semaphore(1);
public replicate() {
if (lock.tryAcquire()) {
try {
// basic setup
Thread t = new Thread(new Runnable() {
public void run() {
try {
// long running process
} catch Exception (e) {
// handle the exceptions
} finally {
lock.release();
}
}
})
t.start();
} catch (Exception e) {
// in case something goes wrong
// before the thread starts
lock.release();
}
} else {
throw new IllegalStateException("already replicating");
}
}
}
public class ReplicatorRunnerInvocator {
public void someMethod() {
try {
ReplicatorRunner replicator = new ReplicatorRunner();
replicator.replicate();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
}
Without looking at the specifics of the ReentrantLock, it occurs to me that this prevention of multiple simultaneous replication routines will be limited to a single JVM instance.
If another instance of the class is kicked off in a separate JVM, then you might be in trouble.
Why not put a lock mechanism on the database? i.e. A row in a control table that is set to a value depicting whether or not the replication is busy running, and reset the value when the replication is finished.
take a look at the Semaphore class here or mark the method as synchronized
the thread executing the method at any given time owns a lock on it avoiding other threads to call the method until its execution ends.
Edit: if you want the other threads to fail, you could use a Lock, and test if the lock is avaible by the tryLock method.

Categories