Skip to content

Commit 0698fcb

Browse files
committed
Prohibit blocking operations in IO threads
This commit makes blocking operations like `Session#run()` throw `IllegalStateException` when executed by Netty event loop IO thread. It's needed because blocking operations are implemented on top of async operations, they simply wait for `Future` to complete by calling `Future#get()`. For example `session.run("CREATE ()")` delegates to `session#runAsync("CREATE ()")` and waits for it to complete. Blocking operation in IO thread might result in this thread waiting for itself to read from network. This will result in deadlocks. Users should avoid calling blocking API methods when chaining `CompletionStage`s returned from async API methods. All operations within a single chain of `CompletionStage` should be async.
1 parent 0bfa545 commit 0698fcb

File tree

7 files changed

+357
-11
lines changed

7 files changed

+357
-11
lines changed

driver/src/main/java/org/neo4j/driver/internal/async/BootstrapFactory.java

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,7 @@
2020

2121
import io.netty.bootstrap.Bootstrap;
2222
import io.netty.channel.ChannelOption;
23-
import io.netty.channel.nio.NioEventLoopGroup;
24-
import io.netty.channel.socket.nio.NioSocketChannel;
23+
import io.netty.channel.EventLoopGroup;
2524

2625
public final class BootstrapFactory
2726
{
@@ -31,19 +30,19 @@ private BootstrapFactory()
3130

3231
public static Bootstrap newBootstrap()
3332
{
34-
return newBootstrap( new NioEventLoopGroup() );
33+
return newBootstrap( EventLoopGroupFactory.newEventLoopGroup() );
3534
}
3635

3736
public static Bootstrap newBootstrap( int threadCount )
3837
{
39-
return newBootstrap( new NioEventLoopGroup( threadCount ) );
38+
return newBootstrap( EventLoopGroupFactory.newEventLoopGroup( threadCount ) );
4039
}
4140

42-
private static Bootstrap newBootstrap( NioEventLoopGroup eventLoopGroup )
41+
private static Bootstrap newBootstrap( EventLoopGroup eventLoopGroup )
4342
{
4443
Bootstrap bootstrap = new Bootstrap();
4544
bootstrap.group( eventLoopGroup );
46-
bootstrap.channel( NioSocketChannel.class );
45+
bootstrap.channel( EventLoopGroupFactory.channelClass() );
4746
bootstrap.option( ChannelOption.SO_KEEPALIVE, true );
4847
bootstrap.option( ChannelOption.SO_REUSEADDR, true );
4948
return bootstrap;
Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,150 @@
1+
/*
2+
* Copyright (c) 2002-2017 "Neo Technology,"
3+
* Network Engine for Objects in Lund AB [http://neotechnology.com]
4+
*
5+
* This file is part of Neo4j.
6+
*
7+
* Licensed under the Apache License, Version 2.0 (the "License");
8+
* you may not use this file except in compliance with the License.
9+
* You may obtain a copy of the License at
10+
*
11+
* http://www.apache.org/licenses/LICENSE-2.0
12+
*
13+
* Unless required by applicable law or agreed to in writing, software
14+
* distributed under the License is distributed on an "AS IS" BASIS,
15+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16+
* See the License for the specific language governing permissions and
17+
* limitations under the License.
18+
*/
19+
package org.neo4j.driver.internal.async;
20+
21+
import io.netty.bootstrap.Bootstrap;
22+
import io.netty.channel.Channel;
23+
import io.netty.channel.EventLoopGroup;
24+
import io.netty.channel.nio.NioEventLoopGroup;
25+
import io.netty.channel.socket.nio.NioSocketChannel;
26+
import io.netty.util.concurrent.DefaultThreadFactory;
27+
import io.netty.util.concurrent.FastThreadLocalThread;
28+
29+
import java.util.concurrent.Executor;
30+
import java.util.concurrent.Future;
31+
import java.util.concurrent.ThreadFactory;
32+
33+
import org.neo4j.driver.v1.Session;
34+
35+
/**
36+
* Manages creation of Netty {@link EventLoopGroup}s, which are basically {@link Executor}s that perform IO operations.
37+
*/
38+
public final class EventLoopGroupFactory
39+
{
40+
private static final String THREAD_NAME_PREFIX = "Neo4jDriverIO";
41+
private static final int THREAD_PRIORITY = Thread.MAX_PRIORITY;
42+
43+
private EventLoopGroupFactory()
44+
{
45+
}
46+
47+
/**
48+
* Get class of {@link Channel} for {@link Bootstrap#channel(Class)} method.
49+
*
50+
* @return class of the channel, which should be consistent with {@link EventLoopGroup}s returned by
51+
* {@link #newEventLoopGroup()} and {@link #newEventLoopGroup(int)}.
52+
*/
53+
public static Class<? extends Channel> channelClass()
54+
{
55+
return NioSocketChannel.class;
56+
}
57+
58+
/**
59+
* Create new {@link EventLoopGroup} with specified thread count. Returned group should by given to
60+
* {@link Bootstrap#group(EventLoopGroup)}.
61+
*
62+
* @param threadCount amount of IO threads for the new group.
63+
* @return new group consistent with channel class returned by {@link #channelClass()}.
64+
*/
65+
public static EventLoopGroup newEventLoopGroup( int threadCount )
66+
{
67+
return new DriverEventLoopGroup( threadCount );
68+
}
69+
70+
/**
71+
* Create new {@link EventLoopGroup} with default thread count. Returned group should by given to
72+
* {@link Bootstrap#group(EventLoopGroup)}.
73+
*
74+
* @return new group consistent with channel class returned by {@link #channelClass()}.
75+
*/
76+
public static EventLoopGroup newEventLoopGroup()
77+
{
78+
return new DriverEventLoopGroup();
79+
}
80+
81+
/**
82+
* Assert that current thread is not an event loop used for async IO operations. This check is needed because
83+
* blocking API methods like {@link Session#run(String)} are implemented on top of corresponding async API methods
84+
* like {@link Session#runAsync(String)} using basically {@link Future#get()} calls. Deadlocks might happen when IO
85+
* thread executes blocking API call and has to wait for itself to read from the network.
86+
*
87+
* @throws IllegalStateException when current thread is an event loop IO thread.
88+
*/
89+
public static void assertNotInEventLoopThread() throws IllegalStateException
90+
{
91+
if ( Thread.currentThread() instanceof DriverThread )
92+
{
93+
throw new IllegalStateException(
94+
"Blocking operation can't be executed in IO thread because it might result in a deadlock. " +
95+
"Please do not use blocking API when chaining futures returned by async API methods." );
96+
}
97+
}
98+
99+
/**
100+
* Same as {@link NioEventLoopGroup} but uses a different {@link ThreadFactory} that produces threads of
101+
* {@link DriverThread} class. Such threads can be recognized by {@link #assertNotInEventLoopThread()}.
102+
*/
103+
private static class DriverEventLoopGroup extends NioEventLoopGroup
104+
{
105+
DriverEventLoopGroup()
106+
{
107+
}
108+
109+
DriverEventLoopGroup( int nThreads )
110+
{
111+
super( nThreads );
112+
}
113+
114+
@Override
115+
protected ThreadFactory newDefaultThreadFactory()
116+
{
117+
return new DriverThreadFactory();
118+
}
119+
}
120+
121+
/**
122+
* Same as {@link DefaultThreadFactory} created by {@link NioEventLoopGroup} by default, except produces threads of
123+
* {@link DriverThread} class. Such threads can be recognized by {@link #assertNotInEventLoopThread()}.
124+
*/
125+
private static class DriverThreadFactory extends DefaultThreadFactory
126+
{
127+
DriverThreadFactory()
128+
{
129+
super( THREAD_NAME_PREFIX, THREAD_PRIORITY );
130+
}
131+
132+
@Override
133+
protected Thread newThread( Runnable r, String name )
134+
{
135+
return new DriverThread( threadGroup, r, name );
136+
}
137+
}
138+
139+
/**
140+
* Same as default thread created by {@link DefaultThreadFactory} except this dedicated class can be easily
141+
* recognized by {@link #assertNotInEventLoopThread()}.
142+
*/
143+
private static class DriverThread extends FastThreadLocalThread
144+
{
145+
DriverThread( ThreadGroup group, Runnable target, String name )
146+
{
147+
super( group, target, name );
148+
}
149+
}
150+
}

driver/src/main/java/org/neo4j/driver/internal/util/Futures.java

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@
2626
import java.util.concurrent.ExecutionException;
2727
import java.util.concurrent.Future;
2828

29+
import org.neo4j.driver.internal.async.EventLoopGroupFactory;
30+
2931
public final class Futures
3032
{
3133
private Futures()
@@ -73,12 +75,9 @@ public static <T> CompletableFuture<T> failedFuture( Throwable error )
7375

7476
public static <V> V getBlocking( CompletionStage<V> stage )
7577
{
76-
Future<V> future = stage.toCompletableFuture();
77-
return getBlocking( future );
78-
}
78+
EventLoopGroupFactory.assertNotInEventLoopThread();
7979

80-
public static <V> V getBlocking( Future<V> future )
81-
{
80+
Future<V> future = stage.toCompletableFuture();
8281
boolean interrupted = false;
8382
try
8483
{
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
/*
2+
* Copyright (c) 2002-2017 "Neo Technology,"
3+
* Network Engine for Objects in Lund AB [http://neotechnology.com]
4+
*
5+
* This file is part of Neo4j.
6+
*
7+
* Licensed under the Apache License, Version 2.0 (the "License");
8+
* you may not use this file except in compliance with the License.
9+
* You may obtain a copy of the License at
10+
*
11+
* http://www.apache.org/licenses/LICENSE-2.0
12+
*
13+
* Unless required by applicable law or agreed to in writing, software
14+
* distributed under the License is distributed on an "AS IS" BASIS,
15+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16+
* See the License for the specific language governing permissions and
17+
* limitations under the License.
18+
*/
19+
package org.neo4j.driver.internal.async;
20+
21+
import io.netty.channel.EventLoopGroup;
22+
import io.netty.channel.nio.NioEventLoopGroup;
23+
import io.netty.channel.socket.nio.NioSocketChannel;
24+
import io.netty.util.concurrent.Future;
25+
import org.junit.After;
26+
import org.junit.Test;
27+
28+
import java.util.concurrent.ExecutionException;
29+
30+
import static java.util.concurrent.TimeUnit.SECONDS;
31+
import static org.hamcrest.Matchers.instanceOf;
32+
import static org.hamcrest.Matchers.is;
33+
import static org.junit.Assert.assertEquals;
34+
import static org.junit.Assert.assertThat;
35+
import static org.junit.Assert.fail;
36+
import static org.neo4j.driver.internal.util.Iterables.count;
37+
import static org.neo4j.driver.internal.util.Matchers.blockingOperationInEventLoopError;
38+
39+
public class EventLoopGroupFactoryTest
40+
{
41+
private EventLoopGroup eventLoopGroup;
42+
43+
@After
44+
public void tearDown()
45+
{
46+
if ( eventLoopGroup != null )
47+
{
48+
eventLoopGroup.shutdownGracefully().syncUninterruptibly();
49+
}
50+
}
51+
52+
@Test
53+
public void shouldReturnCorrectChannelClass()
54+
{
55+
assertEquals( NioSocketChannel.class, EventLoopGroupFactory.channelClass() );
56+
}
57+
58+
@Test
59+
public void shouldCreateEventLoopGroupWithSpecifiedThreadCount()
60+
{
61+
int threadCount = 2;
62+
eventLoopGroup = EventLoopGroupFactory.newEventLoopGroup( threadCount );
63+
assertEquals( threadCount, count( eventLoopGroup ) );
64+
assertThat( eventLoopGroup, instanceOf( NioEventLoopGroup.class ) );
65+
}
66+
67+
@Test
68+
public void shouldCreateEventLoopGroup()
69+
{
70+
eventLoopGroup = EventLoopGroupFactory.newEventLoopGroup();
71+
assertThat( eventLoopGroup, instanceOf( NioEventLoopGroup.class ) );
72+
}
73+
74+
@Test
75+
public void shouldAssertNotInEventLoopThread() throws Exception
76+
{
77+
eventLoopGroup = EventLoopGroupFactory.newEventLoopGroup( 1 );
78+
79+
// current thread is not an event loop thread, assertion should not throw
80+
EventLoopGroupFactory.assertNotInEventLoopThread();
81+
82+
// submit assertion to the event loop thread, it should fail there
83+
Future<?> assertFuture = eventLoopGroup.next().submit( EventLoopGroupFactory::assertNotInEventLoopThread );
84+
try
85+
{
86+
assertFuture.get( 30, SECONDS );
87+
fail( "Exception expected" );
88+
}
89+
catch ( ExecutionException e )
90+
{
91+
assertThat( e.getCause(), is( blockingOperationInEventLoopError() ) );
92+
}
93+
}
94+
}

driver/src/test/java/org/neo4j/driver/internal/util/Matchers.java

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -260,6 +260,26 @@ public void describeTo( Description description )
260260
};
261261
}
262262

263+
public static Matcher<Throwable> blockingOperationInEventLoopError()
264+
{
265+
return new TypeSafeMatcher<Throwable>()
266+
{
267+
@Override
268+
protected boolean matchesSafely( Throwable error )
269+
{
270+
return error instanceof IllegalStateException &&
271+
error.getMessage() != null &&
272+
error.getMessage().startsWith( "Blocking operation can't be executed in IO thread" );
273+
}
274+
275+
@Override
276+
public void describeTo( Description description )
277+
{
278+
description.appendText( "IllegalStateException about blocking operation in event loop thread " );
279+
}
280+
};
281+
}
282+
263283
private static boolean contains( AddressSet set, BoltServerAddress address )
264284
{
265285
BoltServerAddress[] addresses = set.toArray();

0 commit comments

Comments
 (0)