S
S
synapse_people2016-01-21 14:48:04
Java
synapse_people, 2016-01-21 14:48:04

How to synchronize login method?

There is a remote server, when connecting to it, the login object is loaded from it (an object and an object, no more, and that's it), then this object can be sent a login method that will log into the account on the remote server, respectively. the answer also comes in another thread. It turns out that the object is loaded in 1 thread, the login method is called in another, the answer comes in the third. And you need to collect this answer about the result in 1 thread, in the one in which the login method was called and return the answer in the same place. IMPORTANT: The server may not respond, so listeners are not an option, and they will be called in different threads.
How I tried to do: Option 1 , using Semaphore.
I made 1 semaphore for each event: the object is loaded, there is a response from the server about the entrance, the account is loaded (total = 3 semaphores).
That is, the scheme in this case is as follows: I capture the first semaphore (login method), send a packet to the server and capture the semaphore that the response from the server has arrived, then I check it and capture 1 more semaphore that the account (profile) is loaded.
Some kind of crutch in general.
Option 2 reentrantlock and condition.
Here I create 1 lock for the login method and 2 conditions, the first is that the answer came from the server, the second is that the account has loaded.

private final Lock loginLock = new ReentrantLock(true);
private final Condition whenLoginResponse = loginLock.newCondition();
===========================
//Колбэк нужно вызвать в том же потоке, в котором вызывали doLogin.
public void doLogin(String login, String password, final LoginResultCallback callback) {
  loginLock.lock();//локаем метод, чтобы другие потоки не могли вызвать метод входа. Верно же?

  try {
    ... некоторые проверки, чтобы в акк уже не вошли ...
    ... отправка пакета ВХОДА на сервер ...

    ... ждем ответ с сервера...
    whenLoginResponse.await(); <- Тут ничего не отпускает(дальше не идет),
почему-то ждет вечно, хотя whenLoginResponse.signal() был вызван 100%.

    ... логика проверок ответа от сервера (верный ли был пароль, логин, не в блоке
 ли акк и т.д.) ...

    ... тут по аналогии с whenLoginResponse.await() нужно подождать загрузки профиля...

    callback.onLoginOk(client); <- тут вызывается метод, что в акк зашло.
    ИЛИ не зашло(не важно):
    callback.onLoginFailed(client, LoginFailedCause.BLOCKED, null);
  } finally {
    loginLock.unlock();
  }
}

When a response comes from the server, the signal method is called:
whenLoginResponse.signal();
Help with advice and pseudo-code. Thanks in advance!
UP: Once again, the callback needs to be called on the same thread that called doLogin, so that while the login process is in progress, other threads can NOT call doLogin in parallel..

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question