Print FooBar Alternately

Prem Parmar
2 min readJul 13, 2022

Suppose you are given the following code:

class FooBar {
public void foo() {
for (int i = 0; i < n; i++) {
print("foo");
}
}
public void bar() {
for (int i = 0; i < n; i++) {
print("bar");
}
}
}

The same instance of FooBar will be passed to two different threads:

  • thread A will call foo(), while
  • thread B will call bar().

Modify the given program to output "foobar" n times.

Example 1:

Input: n = 1
Output: "foobar"
Explanation: There are two threads being fired asynchronously. One of them calls foo(), while the other calls bar().
"foobar" is being output 1 time.

Example 2:

Input: n = 2
Output: "foobarfoobar"
Explanation: "foobar" is being output 2 times.

Let us solve this problem by using Semaphore, It has two methods acquire(), release(). We will use this methods here. While initializing Semaphore object, you need to pass how many threads can parallelly use that resource via permits.

You can see from above image that two semaphore objects are created while initializing. foo object has 1 permit whereas bar object has 0 permits. Due to this, 1 thread can use resource via foo’s object. It doesn’t require any prior release().

bar object has 0 permits so that it requires prior release() and it is done after the printing of “foo”.

Another approach is using volatile keyword (~ updated value is readable by different thread who is accessing through same object), Please check below

Using Atomic Class, It’s same as volatile keyword. If you know what is volatile keyword then atomic class is easy to understand. New thread will get updated value.

That’s it for today !! If you have any doubt related to this, Please feel free to ask any questions / queries in comment section.

Have a nice day 🍻!!

--

--

Prem Parmar

Software Engineer, having 3 years of experience in Ecommerce / HCM domain Product based company.