Returning to interview questions

There is a lot of types of interview. One is a #developer-in-a-vacuum type, where you are getting questions on algorithms and data structures and system architecture. The interviewers of this type couldn’t care less about your previous experience or the frameworks you know or even the language you use to code. They think of all those things as changeable; what is not changeable are your problem-solving skills, as they call it. Problem is, unless you are an algorithms fan you probably won’t be able to classify a previously unseen task quickly and therefore won’t be able to select the algorithm for it.

This is mainly what large companies like Google and Amazon do.

What do lesser companies do? Well, they do it the opposite way. They will ask you things that you have learned in a uni, or in college, and have happily forgotten afterwards. They will ask you about multithreading  on a basic level, none of your fancy executors and thread pools please, tell me how object.wait() works? Aha, and what will happen if two threads are trying to call it on the same object? And what about generics, can you use a <? extends ClassA> when you declare a generic class? really? a question mark? and can you use a generic type in a method if your class is not generic? and what is volatile and what if two threads are reading and updating from it? and where are strings allocated? they ARE objects right?

We have been looking for a Java programmer recently and during the interviews I realized I have a lot of gaps in my basics, due to the fact that I generally don’t use these in my work and I haven’t been interviewing for a long time. I am happy with my job, so I haven’t. But now I’ve realized that I would miss some of such questions if it was me sitting there being interviewed. I, with my 10+ years of experience, would fall on my face.

So being a smart person that I am (in case someone missed the irony, this IS cruel irony!), I went and registered for a job interview. I wanted to discover the areas I’m rusty with and get some of that interview experience back. I don’t want to change my job but who knows what can happen, right? Especially with the war on.

Well anyway, so I went to the interview, and guess what, I fell right flat on my face! Not a pretty sight, I am telling you. Well it was not as bad as I’m making it sound really, but still it was less then I expected. But – what doesn’t kill you makes a great blog post, right?

So I am going to brush up on some basics here. Multithreading! Java, as I am  a Java developer first of all.

So, how can one protect the data from being accessed and changed by two or more threads at once, potentially providing unexpected results or errors? Well, in Java you have several methods:

  • volatile. Applies to a variable. Means that you think that variable might be accessed by several threads, so you don’t want any of them to cache the value producing potentially unexpected results. This means it’ll always be read from main memory. Changes to a volatile variable are always visible to other threads. Still, though the read and write to the volatile variable are atomic, the read-then-write (like an increment) operation  is not. Therefore, you might want to use a special class for this kind of an operation, for example an AtomicInteger with its incrementAndGet() method.
  • syncronized. Applies to a method or a block. If it’s a block, then you choose the object that the block is locking on. If it’s a method, the lock is the object instance itself.

And now the question that tripped me up somewhat.
If i synchronized two methods on the same class, can they run simultaneously when called by two different threads?
I hope that my boss doesn’t read this now. (If you do, please try to unsee it. I’m better than that, really). But somehow I got in my mind that if that was one method, surely another thread would have to wait, but different methods? I hesitated, looking for a trick. WRONG! There was no trick. It’s all the same, one method or two, if both are syncronized.

You can see it up there right? If it’s a method, the lock is the object instance itself. Meaning that, thread 1 comes in and says, hello I want a lock on you to run this first method please, can I have it? Yes the object says, I am free! Then thread 2 comes in and thread 1 still holds the lock. Thread 2 says, hello can I have a lock on you to run this other method?

What does the object say?
NO!
Respectfully, you have to wait, as I am not free.

It only takes a few minutes to whip up some code proving this point.

package interview;

import java.util.Date;

/**
 * User: marina
 * Date: 9/27/14
 */
public class ThreadChecker {
    public synchronized void methodA() throws InterruptedException {
        System.out.println(new Date() + &quot; Method A called by &quot; + Thread.currentThread().getName());
        Thread.sleep(3000);
    }

    public synchronized void methodB() throws InterruptedException {
        System.out.println(new Date() + &quot; Method B called by &quot; + Thread.currentThread().getName());
        Thread.sleep(3000);
    }

    private static ThreadChecker checker = new ThreadChecker();

    public static void main(String[] args) {
        new Thread1().start();
        new Thread2().start();
    }

    private static class Thread1 extends Thread {
        private Thread1() {
            super(new Runnable() {
                @Override
                public void run() {
                    try {
                        System.out.println(new Date() + &quot; Thread &quot; + Thread.currentThread().getName() + &quot; is run&quot;);
                        checker.methodA();
                    }
                    catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }, &quot;Thread1&quot;);
        }
    }

    private static class Thread2 extends Thread {
        private Thread2() {
            super(new Runnable() {
                @Override
                public void run() {
                    try {
                        System.out.println(new Date() + &quot; Thread &quot; + Thread.currentThread().getName() + &quot; is run&quot;);
                        checker.methodB();
                    }
                    catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }, &quot;Thread2&quot;);
        }
    }
}

When you run it this is what you’re going to get:

Sat Sep 27 13:39:33 EEST 2014 Thread Thread1 is run
Sat Sep 27 13:39:33 EEST 2014 Thread Thread2 is run
Sat Sep 27 13:39:33 EEST 2014 Method A called by Thread1
Sat Sep 27 13:39:36 EEST 2014 Method B called by Thread2

You can see it right? Threads started at the same time, but the method B is run three seconds later. Thread 2 had to wait on the object lock while Thread 1 was running method A.

What would we have if they called the same method? Same thing.

Sat Sep 27 13:41:19 EEST 2014 Thread Thread1 is run
Sat Sep 27 13:41:19 EEST 2014 Thread Thread2 is run
Sat Sep 27 13:41:19 EEST 2014 Method A called by Thread1
Sat Sep 27 13:41:22 EEST 2014 Method A called by Thread2

Duh.
More interview questions to come! I haven’t finished with my gaps yet!

Advertisements

About Maryna Cherniavska

I have productively spent 10+ years in IT industry, designing, developing, building and deploying desktop and web applications, designing database structures and otherwise proving that females have a place among software developers. And this is a good place.
This entry was posted in java and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s