Groovy multi tasking - multithreading

I am trying the execute the below code in which four threads are running.
Each thread trying to add the one character to mylist. After each run, there should be 4 elements in the list in any order. But, when this code is run in jenkin console, getting each time different number of elements. i.e, [A, B, Null], [C,null,D],[A,B,C,D].
It seem like some synchronization issue due to multi tasking. I have tried adding method add element to list using synchronize keyword but that didn't help.
class Globals {
static def mylist=[]
}
class TestMultiThreadExecution implements Runnable
{
String name;
public TestMultiThreadExecution(String name) {
this.name = name;
}
//#Override
public void run() {
println "${name} Step 1"
Globals.mylist.push("${name}")
}
}
Globals.mylist.clear()
Thread thread1 = new Thread(new TestMultiThreadExecution("A"));
thread1.start();
Thread thread2 = new Thread(new TestMultiThreadExecution("B"));
thread2.start();
Thread thread3 = new Thread(new TestMultiThreadExecution("C"));
thread3.start();
Thread thread4 = new Thread(new TestMultiThreadExecution("D"));
thread4.start();
thread1.join();
thread2.join();
thread3.join();
thread4.join();
println Globals.mylist

It is because, list is being concurrently accessed and modified by 4 threads.
You can fix it by changing list type to CopyOnWriteArrayList as shown below.
So, the only change in the above code is to change list type in the Globals class. Here is the changed code snippet.
import java.util.concurrent.CopyOnWriteArrayList
class Globals {
static def mylist = [] as CopyOnWriteArrayList
}
By the, it would be lot easier in groovy to deal with threads. May be you can refer a sample

Related

How do we run multiple functions concurrently in Scala?

This is a scala code I'm trying to write for processing a function multiple times concurrently with two different parameters. However, I notice that the functions are being executed one by one and not both at same time.
class Method1 extends Thread {
override def run(): Unit ={
println("Hello, Current running is Thread No. " + Thread.currentThread().getName )
Function("Parameter 1")
Function("Parameter 2")
}
}
object Obj extends App {
for (x <- 1 to 4){
val th1 = new Method1()
th1.setName(x.toString)
th1.start()
}
}
val a = Array("Justanormalarray")
Obj.main(a)
How to achieve this? Sorry for being dumb but all tutorials I seen only explains a very basic level that multithreading can be achieved by extending thread class or by using runnable interface, but doesn't seem to clear this up (i.e. how to actually execute multiple stuff at same time)

Does a thread acquiring monitor lock of object also acquires the object lock of superclass?

When a thread acquires monitor lock of an object (say class B) does it acquires the monitor lock of the object belonging to it's superclass (say class A, where B extends A) ?
Observation #1 - When a thread (that owns the monitor lock of derived object B through synchronized method) calls wait() inside superclass A, the second thread acquires object B's monitor lock and goes for waiting in A. Finally, both threads exit B's object monitor at the same time.
My understanding is a thread should invoke wait() on an object whose lock it owns, else this will lead to IllegalMonitorStateException. The reason that there being no exception while wait() called inside A's instance method, does it mean the thread owning the B object lock also owns the lock of A object, it's superclass ?
Checked articles on synchronization & intrinsic locks - What does intrinsic lock actually mean for a Java class?
https://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html
public class Obs2 {
public static void main(String[] args) {
A a = new B();
Thread t1 = new Thread(a);
Thread t2 = new Thread(a);
t1.start(); t2.start();
}
}
class A implements Runnable {
public void run() {
try {
wait(2000); // OK; No IllegalMonitorStateException
} catch (InterruptedException e) {}
}
}
class B extends A {
#Override
public synchronized void run() {
super.run();
}
}
Observation #2 - When a thread (that owns monitor lock of object A through synchronized method) invokes wait() inside any arbitrary class C, it raises an IllegalMonitorStateException.
This suggests the thread calls wait() on C's object whereas it owns the lock for object A which are different. Hence the exception.
public class Obs2 {
public static void main(String[] args) {
A a = new A();
Thread t1 = new Thread(a);
Thread t2 = new Thread(a);
t1.start(); t2.start();
}
}
class A implements Runnable {
public synchronized void run() {
(new C()).display(this);
}
}
class C {
public void display() {
try {
wait(2000); //--> will lead to IllegalMonitorStateException
} catch (InterruptedException e) {}
}
}
Why this inherent discrepancy in the way the object monitor lock behaves for superclass in comparison to any other class ?
Is my understanding regarding object monitor lock missing anything?
I'm not exactly sure if your question makes any sense. There's no such thing as a "superclass" instance because the instance of the subclass is one and the same as the instance of its superclass, otherwise you would be instantiating several objects each time you use the new keyword. That is also the reason why you can't do something like:
synchronized (super) {
}
Ultimately, the ability to use wait and notify[All] belongs to Object (as they are final methods), which is the super-super class of every class. You can think of synchronizing on this as synchronizing on the monitor belonging to Object, as intrinsic locks are associated with objects, not classes (an important distinction is that an intrinsic lock associated with a Class object may be acquired).
Therefore, since both A and B are the same instance of Object, it doesn't matter that you've synchronized in B and call wait from A, they are both referring to the same Object.

Jenkins pipeline script - Thread programming

I am trying to create multiple threads in a jenkins pipeline script. So, I took simple example as below. But it not working. Could you please let me know?
In the below example, jobMap contains a key as a string and value as List of Strings. When I just display the list, the values printed properly, but when I used 3 different ways to create threads and thus to display, it is not working.
for ( item in jobMap )
{
def jobList = jobMap.get(item.key);
**// The following loop is printing the values**
for (jobb in jobList)
{
echo "${jobb}"
}
// Thread Implementation1:
Thread.start
{
for (jobb in jobList)
{
echo "${jobb}"
}
}
// Thread Implementation2:
def t = new Thread({ echo 'hello' } as Runnable)
t.start() ;
t.join();
// Thread Implementation3:
t1 = new Thread( new TestMultiThreadSleep(jobList));
t1.start();
}
class TestMultiThreadSleep implements Runnable {
String jobs;
public TestMultiThreadSleep(List jobs) {
this.jobs = jobs;
}
#Override
public void run()
{
echo "coming here"
for (jobb in jobs)
{
echo "${jobb}"
}
}
}
Jenkins has special step - parallel(). In this step you can build another jobs or call Pipeline code.
It's best to think of Pipeline code as a dialect or subset of Groovy.
The CPS transformer ("continuation-passing style") in the workflow script engine turns the Groovy code into something that can be interpreted in a serialized form, passed between different JVMs, etc.
You can probably imagine that this will not work at all well with threads.
If you need threads, you'll have to work within a #NonCPS annotated class or function. This class or function must not call any CPS groovy code - so it can't invoke closures, access the workflow script context, etc.
That's why using the parallel step is preferable.

How to understand "new {}" syntax in Scala?

I am learning Scala multi-thread programming, and write a simple program through referring a tutorial:
object ThreadSleep extends App {
def thread(body: =>Unit): Thread = {
val t = new Thread {
override def run() = body
}
t.start()
t
}
val t = thread{println("New Therad")}
t.join
}
I can't understand why use {} in new Thread {} statement. I think it should be new Thread or new Thread(). How can I understand this syntax?
This question is not completely duplicated to this one, because the point of my question is about the syntax of "new {}".
This is a shortcut for
new Thread() { ... }
This is called anonymous class and it works just like in JAVA:
You are here creating a new thread, with an overriden run method. This is useful because you don't have to create a special class if you only use it once.
Needs confirmation but you can override, add, redefine every method or attribute you want.
See here for more details: https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html
By writing new Thread{} your creating an anonymous subclass of Thread where you're overriding the run method. Normally, you'd prefer to create a subclass of Runnable and create a thread with it instead of subclassing Thread
val r = new Runnable{ override def run { body } }
new Thread(r).start
This is usually sematincally more correct, since you'd want to subclass Thread only if you were specializing the Thread class more, for example with an AbortableThread. If you just want to run a task on a thread, the Runnable approach is more adequate.

Threading from within a class with static and non-static methods

Let's say I have
class classA {
void someMethod()
{
Thread a = new Thread(threadMethod);
Thread b = new Thread(threadMethod);
a.Start();
b.Start();
a.Join();
b.Join();
}
void threadMethod()
{
int a = 0;
a++;
Console.Writeline(a);
}
}
class classB {
void someMethod()
{
Thread a = new Thread(threadMethod);
Thread b = new Thread(threadMethod);
a.Start();
b.Start();
a.Join();
b.Join();
}
static void threadMethod()
{
int a = 0;
a++;
Console.Writeline(a);
}
}
Assuming that in classA and classB, the contents of threadMethod have no effect to anything outside of its inner scope, does making threadMethod in classB static have any functional difference?
Also, I start two threads that use the same method in the same class. Does each method get its own stack and they are isolated from one another in both classA and classB?
Does again the static really change nothing in this case?
Methods don't have stacks, threads do. In your example threadMethod only uses local variables which are always private to the thread executing the method. It doesn't make any difference if the method is static or not as the method isn't sharing any data.
In this case there is no functional difference. Each thread gets it's own stack
Maybe you can be a little more clear. It doesn't matter if the function is declared static or not in most languages. Each thread has its own private statck.
Each thread would get it's own stack. There is no functional difference that I can tell between the two.
The only difference (obviously) is that the static version would be unable to access member functions/variables.

Resources